有没有办法利用Jackson ObjectMapper从JSON中一一读取对象

问题描述

我想知道是否可以使用 ObjectMapper 中的 Jackson 来逐一读取事件。

我有一个大型 JSON 文件,其中包含许多我需要转换为 XML 的事件。我不想将完整的 JSON 事件加载到我的内存中,也不想一个一个地处理事件。因此,我正在使用 Java Jackson 库,它可以遍历 JSON 文件并一次获取一个 JSON 事件,然后我可以将其转换为 XML。这样,一次只有一个事件会被加载到内存中。

我知道我可以使用 Jackson 的 JsonParser,它会一个一个地遍历 JSON 文件,但那样的话,我需要处理很多事情。

我有从 XSD 创建的 Java 类(使用 JAXB2),所以我想使用 ObjectMapper 中的 Jackson 类,它可以将每个事件直接映射到其相应的 Java 类稍后我可以使用 Marshalling 方法转换为相应的 XML。

我不明白如何使用 ObjectMapper 逐一读取事件并将其分配给相应的 Java 类。

以下是我的 JSON 文件的简单版本:(这是一个示例 JSON,我的原始 JSON 非常复杂)

{
   "@context":"https://context.org/context.jsonld","isA":"SchoolManagement","format":"application/ld+json","schemaVersion":"2.0","creationDate":"2021-04-21T10:10:09+00:00","body":{
      "members":[
         {
            "isA":"student","name":"ABCS","class":10,"coaching":[
              "XSJSJ","IIIRIRI"
            ],"dob":"1995-04-21T10:10:09+00:00"
         },{
            "isA":"teacher","department":"computer science","school":{
              "name":"ABCD School"
            },{
            "isA":"boardMember","board":"schoolboard","dob":"1995-04-21T10:10:09+00:00"
         }
      ]
   }
}

我想一一读取“members”数组中的事件,检查是否是“student”、“teacher”等,然后赋值给对应的class。

public class Main {

  public static void main(String[] args) throws JsonParseException,JsonMappingException,IOException,JAXBException {

    final ObjectMapper objectMapper = new ObjectMapper();

    // Accept the Null values for some fields
    objectMapper.setSerializationInclusion(Include.NON_NULL);

    // If any unkNown properties found then do not fail
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNowN_PROPERTIES,false);

    //Here I want to read the element within an array 
    Student event = objectMapper.readValue(Main.class.getResourceAsstream("/events.json"),Student.class);
    System.out.println(event);

  }

}

解决方法

我将告诉您如何读取 JSON 文件并获取每个键及其值,如何将其放入 XML 文件将在您手中。

1 根据需要为 JSON 文件创建任意数量的 POJO(您可以在此处自动生成:https://www.jsonschema2pojo.org/

2 代码:

    ObjectMapper objectMapper = new ObjectMapper();
            School school = new School();
            File file = new File("school.json");
            
            //With this you map the JSON file and get the data
            try {
                school = objectMapper.readValue(file,School.class);
                
                String JSONOutputCustomer = objectMapper.writeValueAsString(school.getBody());
                System.out.println(JSONOutputCustomer);
                
            } catch (IOException e) {
                e.printStackTrace();
            }
            /*With this you list the info inside of the key Body.
I just did it with body,but you can do it with any key you want,as for example Member,you can list only the information of just one member insted all of them doing the same as the example below*/

            List<Body> bodyList = new ArrayList<Body>();
            
            for(Body values : bodyList) {
                System.out.println(values.getMembers());
            }

现在您知道如何获取每个键的值了。

注意:我没有放置 POJO 类,因为它们是 4 并且它的代码太多,您可以从我上面留下的链接中获取

注2:不要怪我拼写错误,我还在学习英语T_T

示例 2

ObjectMapper objectMapper = new ObjectMapper();
Member member = new Member();
        File file = new File("school.json");

try {
            member = objectMapper.readValue(file,Member.class);
            
            String JSONOutputCustomer = objectMapper.writeValueAsString(member);
            System.out.println(JSONOutputCustomer);
        } catch (IOException e) {
            e.printStackTrace();
        }
,

基本上有三种使用 JACKSON2 解析 JSON 的方法,难度各不相同。

  1. ObjectMapper (mapper.readValue()):编写更少的代码 - 应该使用简单的数据绑定,
  2. ObjectMapper(树模型):中等代码 - 应该用于复杂的 JSON
  3. JsonParser(流模型):更多代码 - 需要终极性能时应使用。

您正在寻找树模型。它结合了 JSONParser 的灵活性和 ObjectMapper 的易用性。试试下面的ObjectMapper

//create Object Node using Tree model
ObjectNode event = objectMapper.readTree("/events.json");

//Now access the Json One by One as you like
JsonNode memberNode = json.get("body").get("Members");

There is Nice Mkyong tutorial for the Tree Model

阅读更多: JACKSON2 Offical documentation