我通过调用RestTemplate
获得两种类型的json{"results":[{"testing":{"name":"soham"}},{"testing":{"firstname":"john","lastname":"don"}}]}
现在我正在使用JsonDeserializer
解析数据public class CustomJacksonDeserialize extends JsonDeserializer<Activity> {
@Override
public Activity deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws
IOException, NullPointerException {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode actualObj = objectMapper.readTree(jsonParser.getValueAsString());
return new Activity(actualObj.get("name").asText());
}
}
这是我的班级
@JsonDeserialize(using = CustomJacksonDeserialize.class)
public class Activity {
private String name;
public Activity(String name) {
this.name = name;
}
}
现在我的问题是如何解析这个json。@JsonDeserialize
在这种情况下没有帮助。还有其他选择吗?或者在这种情况下如何使用@JsonDeserialize
。
答案 0 :(得分:0)
您可以像这样修改CustomJacksonDeserialize
:
class CustomJacksonDeserialize extends JsonDeserializer<Activity> {
@Override
public Activity deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException,
NullPointerException {
JsonNode jsonNode = jsonParser.readValueAsTree();
String name=jsonNode.get("results").get(0).get("testing").get("name").asText();
return new Activity(name);
}
}
第二种方法: 或者如果你也可以使用Object mapper本身对这个JSON进行去序列化这不需要CustomJacksonDeserialize:
String jsonString = "{\"results\":[{\"testing\":{\"name\":\"soham\"}},{\"testing\":{\"firstname\":\"john\",\"lastname\":\"don\"}}]}";
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonString);
JsonNode resultNode=jsonNode.get("results");
String name = resultNode.get(0).get("testing").get("name").asText();
Activity activity=new Activity(name);
String firstName= resultNode.get(1).get("testing").get("firstname").asText();
String lastName= resultNode.get(1).get("testing").get("lastname").asText();
Activity2 activity2=new Activity2(firstName, lastName);
注意:我为给定的JSON提取了name
,firstname
和lastname
的值,您可以相应地修改此逻辑。
第三种方法:在这里,我可以遍历JSON数组并创建两个活动的单独对象:
String jsonString = "{\"results\":[{\"testing\":{\"name\":\"soham\"}},{\"testing\":{\"firstname\":\"john\",\"lastname\":\"don\"}}]}";
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonString);
JsonNode resultNode = jsonNode.get("results");
List<Activity> activityList1 = new ArrayList<Activity>();
List<Activity2> activityList2 = new ArrayList<Activity2>();
for (int i = 0; i < resultNode.size(); i++) {
JsonNode testingNode = resultNode.get(i).get("testing");
if (testingNode.has("name")) {
String name = testingNode.get("name").asText();
Activity activity = new Activity(name);
activityList1.add(activity);
}
if (testingNode.has("firstname")) {
String firstName = testingNode.get("firstname").asText();
String lastName = testingNode.get("lastname").asText();
Activity2 activity2 = new Activity2(firstName, lastName);
activityList2.add(activity2);
}
}