0

我必须准备模型以将响应发送到模型。

这是收到的示例 JSON 格式:

{
\\ rest of the model
"Model": {
    "name": "name_01",
    "description": "name_01",
    "features": {
      "name": "feature 01",
      "description": "feature 01"
    }
  }
\\ Rest of the model
}

要发送到 fronEnd 的响应:

{
\\ rest of the model

"model_name":"name_01",
"feature_name":"feature_01"
}
\\ rest of the model

这是我到目前为止实现的:

代码:

@SuppressWarnings("unchecked")
    @JsonProperty("model")
    private void unpackNestedModel(Map<String,Object> model) {
        this.model_name = (String) model.get("name");
        Map<String, Object> model2 = (Map<String, Object>) model.get("features");
        this.feature_name = (String) model2.get("name");
    }

有没有更好的办法?

4

2 回答 2

2

可以通过 解析结果JSONObject,但建议通过 POJO 对象操作 json 结果。

@Test
public void test02() {
    String receivedJson = "{\"Model\":{\"name\":\"name_01\",\"description\":\"name_01\",\"features\":{\"name\":\"feature 01\",\"description\":\"feature 01\"}}}";
    JSONObject receivedObj = JSONObject.parseObject(receivedJson);

    JSONObject model = (JSONObject) receivedObj.get("Model");
    JSONObject features = (JSONObject) model.get("features");

    JSONObject responseObj = new JSONObject();
    responseObj.put("model_name", model.getString("name"));
    responseObj.put("feature_name", features.getString("name"));

    System.out.println(responseObj);
    //output in console
    //{"model_name":"name_01","feature_name":"feature 01"}
}
于 2019-09-24T03:36:06.790 回答
1

假设您正在使用 Jackson 并且您的请求有效负载是这样的:

{
  "Model": {
    "name": "name_01",
    "description": "name_01",
    "features": {
      "name": "feature 01",
      "description": "feature 01"
    }
  }
}

您可以使用以下类来表示它:

@Data
public class RequestData {

    @JsonProperty("Model")
    private Model model;
}
@Data
public class Model {

    private String name;
    private String description;
    private Features features;
}
@Data
public class Features {

    private String name;
    private String description;
}

如果您在 中启用UNWRAP_ROOT_VALUE反序列化功能ObjectMapper,您可以简单地拥有:

@Data
@JsonRootName("Model")
public class Model {

    private String name;
    private String description;
    private Features features;
}
@Data
public class Features {

    private String name;
    private String description;
}

如果您的响应负载是这样的:

{
  "model_name": "name_01",
  "feature_name": "feature_01"
}

你可以有:

@Data
public class ResponseData {

    @JsonProperty("model_name")
    private String modelName;

    @JsonProperty("feature_name")
    private String featureName;
}
于 2019-09-24T13:40:25.590 回答