【问题标题】:How to parse a JSON string to an array using Jackson如何使用 Jackson 将 JSON 字符串解析为数组
【发布时间】:2011-11-06 22:50:09
【问题描述】:

我有一个String,其值如下:

[
  {
    "key1": "value11",
    "key2": "value12"
  },
  {
    "key1": "value21",
    "key2": "value22"
  }
]

还有以下类:

public class SomeClass {
    private String key1;
    private String key2;
    /* ... getters and setters omitted ...*/
}

我想将其解析为List<SomeClass>SomeClass[]

使用JacksonObjectMapper 最简单的方法是什么?

【问题讨论】:

  • 我也遇到过类似的情况,但决定反序列化为 JSONArray 对象而不是对类进行反序列化,因为这样可以避免将来出现类序列化问题。看多了有什么优势吗?

标签: java json jackson


【解决方案1】:

我终于明白了:

ObjectMapper objectMapper = new ObjectMapper();
TypeFactory typeFactory = objectMapper.getTypeFactory();
List<SomeClass> someClassList = objectMapper.readValue(jsonString, typeFactory.constructCollectionType(List.class, SomeClass.class));

【讨论】:

  • 什么是 ObjectMapper?能具体说明一下吗?
  • @hitesh141 ObjectMapper 是 com.fasterxml.jackson.databind.ObjectMapper 的成员
【解决方案2】:

另一个答案是正确的,但为了完整起见,这里有其他方法:

List<SomeClass> list = mapper.readValue(jsonString, new TypeReference<List<SomeClass>>() { });
SomeClass[] array = mapper.readValue(jsonString, SomeClass[].class);

【讨论】:

    【解决方案3】:

    带有数组的完整示例。 将“constructArrayType()”替换为“constructCollectionType()”或您需要的任何其他类型。

    import java.io.IOException;
    
    import com.fasterxml.jackson.core.JsonParseException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.databind.type.TypeFactory;
    
    public class Sorting {
    
        private String property;
    
        private String direction;
    
        public Sorting() {
    
        }
    
        public Sorting(String property, String direction) {
            this.property = property;
            this.direction = direction;
        }
    
        public String getProperty() {
            return property;
        }
    
        public void setProperty(String property) {
            this.property = property;
        }
    
        public String getDirection() {
            return direction;
        }
    
        public void setDirection(String direction) {
            this.direction = direction;
        }
    
        public static void main(String[] args) throws JsonParseException, IOException {
            final String json = "[{\"property\":\"title1\", \"direction\":\"ASC\"}, {\"property\":\"title2\", \"direction\":\"DESC\"}]";
            ObjectMapper mapper = new ObjectMapper();
            Sorting[] sortings = mapper.readValue(json, TypeFactory.defaultInstance().constructArrayType(Sorting.class));
            System.out.println(sortings);
        }
    }
    

    【讨论】:

      【解决方案4】:

      我通过验证 JSONLint.com 上的 json 然后使用 Jackson 来解决这个问题。下面是相同的代码。

       Main Class:-
      
      String jsonStr = "[{\r\n" + "       \"name\": \"John\",\r\n" + "        \"city\": \"Berlin\",\r\n"
                      + "         \"cars\": [\r\n" + "            \"FIAT\",\r\n" + "          \"Toyata\"\r\n"
                      + "     ],\r\n" + "     \"job\": \"Teacher\"\r\n" + "   },\r\n" + " {\r\n"
                      + "     \"name\": \"Mark\",\r\n" + "        \"city\": \"Oslo\",\r\n" + "        \"cars\": [\r\n"
                      + "         \"VW\",\r\n" + "            \"Toyata\"\r\n" + "     ],\r\n"
                      + "     \"job\": \"Doctor\"\r\n" + "    }\r\n" + "]";
      
              ObjectMapper mapper = new ObjectMapper();
      
              MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);
      
              for (MyPojo itr : jsonObj) {
      
                  System.out.println("Val of getName is: " + itr.getName());
                  System.out.println("Val of getCity is: " + itr.getCity());
                  System.out.println("Val of getJob is: " + itr.getJob());
                  System.out.println("Val of getCars is: " + itr.getCars() + "\n");
      
              }
      
      POJO:
      
      public class MyPojo {
      
      private List<String> cars = new ArrayList<String>();
      
      private String name;
      
      private String job;
      
      private String city;
      
      public List<String> getCars() {
          return cars;
      }
      
      public void setCars(List<String> cars) {
          this.cars = cars;
      }
      
      public String getName() {
          return name;
      }
      
      public void setName(String name) {
          this.name = name;
      }
      
      public String getJob() {
          return job;
      }
      
      public void setJob(String job) {
          this.job = job;
      }
      
      public String getCity() {
          return city;
      }
      
      public void setCity(String city) {
          this.city = city;
      } }
      
        RESULT:-
               Val of getName is: John
               Val of getCity is: Berlin
               Val of getJob is: Teacher
               Val of getCars is: [FIAT, Toyata]
      
                Val of getName is: Mark
                Val of getCity is: Oslo
                Val of getJob is: Doctor
                Val of getCars is: [VW, Toyata]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-08
        • 2014-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多