如何使用jackson解析json中嵌套对象和数组的复杂格式数据?-相关文档
jackson是一个流行的Java JSON解析库,可以方便地解析复杂的JSON格式数据。要解析嵌套对象和数组的数据,可以使用jackson中的ObjectMapper类和TypeReference类。首先,创建一个ObjectMapper对象并使用readValue()方法将JSON字符串解析为一个Java对象,然后使用TypeReference类来指定嵌套的对象和数组类型。例如,如果JSON数据包含一个名为"contacts"的数组,数组中包含多个名为"person"的对象,每个对象包含"name"和"address"属性,则可以使用以下代码进行解析:
ObjectMapper mapper = new ObjectMapper(); String jsonStr = "{"contacts":[{"person":{"name":"Alice","address":"123 Main St","phoneNumbers":["555-1212","555-1234"]}},{"person":{"name":"Bob","address":"456 Oak St","phoneNumbers":["555-5678"]}}]}"; Map<String, List<Map<String, Map<String, Object>>>> data = mapper.readValue(jsonStr, new TypeReference<Map<String, List<Map<String, Map<String, Object>>>>>() {}); List<Map<String, Map<String, Object>>> contacts = data.get("contacts"); for (Map<String, Map<String, Object>> contact : contacts) { Map<String, Object> person = contact.get("person"); String name = (String) person.get("name"); String address = (String) person.get("address"); List phoneNumbers = (List) person.get("phoneNumbers"); System.out.println("Name: " + name); System.out.println("Address: " + address); System.out.println("Phone numbers: " + phoneNumbers); }