jackson deserialization json to java-objects

前端 未结 4 809
时光取名叫无心
时光取名叫无心 2020-12-09 08:18

Here is my Java code which is used for the de-serialization, i am trying to convert json string into java object. In doing so i have used the following code:



        
相关标签:
4条回答
  • 2020-12-09 08:44

    You have to change the line

    product userFromJSON = mapper.readValue(userDataJSON, product.class);
    

    to

    product[] userFromJSON = mapper.readValue(userDataJSON, product[].class);
    

    since you are deserializing an array (btw: you should start your class names with upper case letters as mentioned earlier). Additionally you have to create setter methods for your fields or mark them as public in order to make this work.

    Edit: You can also go with Steven Schlansker's suggestion and use

    List<product> userFromJSON =
            mapper.readValue(userDataJSON, new TypeReference<List<product>>() {});
    

    instead if you want to avoid arrays.

    0 讨论(0)
  • 2020-12-09 08:48

    It looks like you are trying to read an object from JSON that actually describes an array. Java objects are mapped to JSON objects with curly braces {} but your JSON actually starts with square brackets [] designating an array.

    What you actually have is a List<product> To describe generic types, due to Java's type erasure, you must use a TypeReference. Your deserialization could read: myProduct = objectMapper.readValue(productJson, new TypeReference<List<product>>() {});

    A couple of other notes: your classes should always be PascalCased. Your main method can just be public static void main(String[] args) throws Exception which saves you all the useless catch blocks.

    0 讨论(0)
  • 2020-12-09 08:48
     JsonNode node = mapper.readValue("[{\"id\":\"value11\",\"name\": \"value12\",\"qty\":\"value13\"},"
    
     System.out.println("id : "+node.findValues("id").get(0).asText());
    

    this also done the trick.

    0 讨论(0)
  • 2020-12-09 08:58

    Your product class needs a parameterless constructor. You can make it private, but Jackson needs the constructor.

    As a side note: You should use Pascal casing for your class names. That is Product, and not product.

    0 讨论(0)
提交回复
热议问题