我必须准备模型才能将响应发送到模型。
这是接收的示例 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");
}
有没有更好的方法?
你可以通过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"}
}
假设您使用的是 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;
}
如果在ObjectMapper
中启用UNWRAP_ROOT_VALUE
反序列化功能,则只需:
@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;
}