简体   繁体   中英

How to convert JSON to Java object

I am using Jackson ObjectMapper I have below JSON and Java Class. I am getting exception. Could someone tell me whats wrong with my Java class

JSON:

{"name":
    [
        {
            "field1":"value1",
            "field2":"value2"
        },
        {
            "field1":"value1",
            "field2":"value2"
        },
        {
            "field1":"value1",
            "field2":"value2"
        }
    ]
}

Java Class: AnyJsonObject.java:

public class AnyJsonObject {
    private List<Name> name;

    public List<Name> getName() {
        return name;
    }

    public void setName(List<Name> name) {
        this.name = name;
    }
}

Name.java:

public class Name {

    @JsonProperty("field1")
    public String fieldOne;

    public String field2;

}

Code:

ObjectMapper mapper = new ObjectMapper();
mapper.readValue(json, AnyJsonObject.class);

I get java.lang.Exception: Error occurred when de-serializing json

In AnyJsonObject class you have following lines:

private List<Name> name;

// wrong place here
public Name getName() {
    return name;
}

You are returning List<Name> type but method signature is public Name getName() . You should fix return type:

public List<Name> getName() {
    return name;
}

Edit:

I have modified your source code and used Jackson 2 lib. Here is my implementation of this task:

Here is class Name :

import com.fasterxml.jackson.annotation.JsonProperty;

public class Name {

    @JsonProperty("field1")
    public String fieldOne;

    @JsonIgnore
    public String field2; // this field will be ignored

    @Override
    public String toString() {
        return "field1: " + fieldOne + ", field2: " + field2;
    }
} 

Here is AnyJsonObject class :

import java.util.List;

public class AnyJsonObject {
    private List<Name> name;

    public List<Name> getName() {
        return name;
    }

    public void setName(List<Name> name) {
        this.name = name;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Name n : name) sb.append(n.toString());

        return sb.toString();
    }
}

And here is Test class :

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;

public class Test {

    public static void main(String[] args) {
        String json = "{\"name\":\n" +
                "    [\n" +
                "        {\n" +
                "            \"field1\":\"value1\",\n" +
                "            \"field2\":\"value2\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"field1\":\"value1\",\n" +
                "            \"field2\":\"value2\"\n" +
                "        },\n" +
                "        {\n" +
                "            \"field1\":\"value1\",\n" +
                "            \"field2\":\"value2\"\n" +
                "        }\n" +
                "    ]\n" +
                "}";

        ObjectMapper mapper = new ObjectMapper();

        try {
            AnyJsonObject any = mapper.readValue(json, AnyJsonObject.class);
            System.out.println(any);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output of execution:

field1: value1, field2: value2field1: value1, field2: value2field1: value1, field2: value2

As an alternative suggest using gson ( https://github.com/google/gson ) It also helps read json to Java object, like:

public List<Class_to_create_json_of> readJsonToObject(String jsonContent) {

    JSONObject json = new JSONObject();
    try {
         json = (JSONObject) new JSONParser().parse(jsonContent);
    } catch (Exception e) {
         handleException(e);
    }
    return gson.fromJson(json.toString(),
                new TypeToken<List<Class_to_create_json_of>>() {}.getType());
}

Class_to_create_json_of is the class that represents your Json - String fields for string values, boolean for boolean, etc.... For example:

{
  "some_key" : "some_velue",
  "some_other_key" : 1,
  "some_third_key" : true
}

public class jsonContent {
   private String some_key;
   private int some_other_key;
   privtae boolean some_third_key;

   public setSome_key(String some_key) {
       this.some_key = some_key;
   }
   public setSome_other_key(int some_other_key) {
      this.some_other_key = some_other_key;
   }
   public setSome_third_key(boolean some_third_key) {
      this.some_third_key = some_third_key;
   }

   public getSome_key() {
       return some_key;
   }
   public getSome_other_key(i) {
      return some_other_key;
   }
   public getSome_third_key() {
      return some_third_key;
   }
}

导入com.fasterxml.jackson.core.JsonProcessingException;导入com.fasterxml.jackson.databind.JavaType;导入com.fasterxml.jackson.databind.JsonNode;导入com.fasterxml.jackson.databind.ObjectMapper;导入com.fasterxml.jackson .databind.node.ArrayNode; public static T jsonToPojo(String jsonData,Class beanType){试试{T t = MAPPER.readValue(jsonData,beanType);返回t;} catch(Exception e){e.printStackTrace();}返回null;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM