使用杰克逊解析器解析Json String

时间:2018-06-22 15:27:55

标签: json jackson

我能够解析以下json:

{
    "jobId": "xxx",
    "jobName": "xxx",
    "jobInput": "xxx"
}

final ObjectMapper mapper = new ObjectMapper();
Map<?, ?> map = mapper.readValue(jsonString, Map.class);

我需要使用java中的jackson解析器来解析以下json字符串。

{
"Test1": {
    "jobId": "xxx",
    "jobName": "xxx",
    "jobInput": "xxx"
  },
"Test2": {
    "jobId": "xxx",
    "jobName": "xxx",
    "jobInput": "xxx"
  }
}

1 个答案:

答案 0 :(得分:2)

使用Jackson,您可以执行以下操作:

ObjectMapper mapper = new ObjectMapper();
TypeReference<Map<String, Object>> typeRef = new TypeReference<Map<String, Object>>() {};
Map<String, Object> data = mapper.readValue(json, typeRef);

如果您希望使用自定义类而不是Map来保存值,请使用:

ObjectMapper mapper = new ObjectMapper();
Data data = mapper.readValue(json, Data.class);
public class Data {

    @JsonProperty("Test1")
    private Job test1;

    @JsonProperty("Test2")
    private Job test2;

    // Default constructor, getters and setters
}
public class Job {

    private String jobId;

    private String jobName;

    private String jobInput;

    // Default constructor, getters and setters
}