我必须准备要发送给模型的模型。
这是接收到的示例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");
}
有更好的方法吗?
答案 0 :(得分:2)
您可以通过JSONObject
解析结果,但建议通过POJO Object操作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"}
}
答案 1 :(得分:1)
假设您正在使用Jackson,并且您的请求有效载荷是这样的:
@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;
}
ObjectMapper
如果您在@Data
@JsonRootName("Model")
public class Model {
private String name;
private String description;
private Features features;
}
中启用了UNWRAP_ROOT_VALUE
反序列化功能,则可以简单地进行以下操作:
@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;
}
您可能会:
if (modal.classList.contains('is-active')) {
body.classList.toggle('is-modal-open');
}