Converting JSON data to Java object

后端 未结 12 1112
春和景丽
春和景丽 2020-11-21 05:11

I want to be able to access properties from a JSON string within my Java action method. The string is available by simply saying myJsonString = object.getJson()

相关标签:
12条回答
  • 2020-11-21 05:40

    Oddly, the only decent JSON processor mentioned so far has been GSON.

    Here are more good choices:

    • Jackson (Github) -- powerful data binding (JSON to/from POJOs), streaming (ultra fast), tree model (convenient for untyped access)
    • Flex-JSON -- highly configurable serialization

    EDIT (Aug/2013):

    One more to consider:

    • Genson -- functionality similar to Jackson, aimed to be easier to configure by developer
    0 讨论(0)
  • 2020-11-21 05:42

    The easiest way is that you can use this softconvertvalue method which is a custom method in which you can convert jsonData into your specific Dto class.

    Dto response = softConvertValue(jsonData, Dto.class);
    
    
    public static <T> T softConvertValue(Object fromValue, Class<T> toValueType) 
    {
        ObjectMapper objMapper = new ObjectMapper();
        return objMapper
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .convertValue(fromValue, toValueType);
    }
    
    0 讨论(0)
  • 2020-11-21 05:43

    Bewaaaaare of Gson! It's very cool, very great, but the second you want to do anything other than simple objects, you could easily need to start building your own serializers (which isn't that hard).

    Also, if you have an array of Objects, and you deserialize some json into that array of Objects, the true types are LOST! The full objects won't even be copied! Use XStream.. Which, if using the jsondriver and setting the proper settings, will encode ugly types into the actual json, so that you don't loose anything. A small price to pay (ugly json) for true serialization.

    Note that Jackson fixes these issues, and is faster than GSON.

    0 讨论(0)
  • 2020-11-21 05:43

    Easy and working java code to convert JSONObject to Java Object

    Employee.java

    import java.util.HashMap;
    import java.util.Map;
    
    import javax.annotation.Generated;
    
    import com.fasterxml.jackson.annotation.JsonAnyGetter;
    import com.fasterxml.jackson.annotation.JsonAnySetter;
    import com.fasterxml.jackson.annotation.JsonIgnore;
    import com.fasterxml.jackson.annotation.JsonInclude;
    import com.fasterxml.jackson.annotation.JsonProperty;
    import com.fasterxml.jackson.annotation.JsonPropertyOrder;
    
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @Generated("org.jsonschema2pojo")
    @JsonPropertyOrder({
    "id",
    "firstName",
    "lastName"
    })
    public class Employee {
    
    @JsonProperty("id")
    private Integer id;
    @JsonProperty("firstName")
    private String firstName;
    @JsonProperty("lastName")
    private String lastName;
    @JsonIgnore
    private Map<String, Object> additionalProperties = new HashMap<String, Object>();
    
    /**
    *
    * @return
    * The id
    */
    @JsonProperty("id")
    public Integer getId() {
    return id;
    }
    
    /**
    *
    * @param id
    * The id
    */
    @JsonProperty("id")
    public void setId(Integer id) {
    this.id = id;
    }
    
    /**
    *
    * @return
    * The firstName
    */
    @JsonProperty("firstName")
    public String getFirstName() {
    return firstName;
    }
    
    /**
    *
    * @param firstName
    * The firstName
    */
    @JsonProperty("firstName")
    public void setFirstName(String firstName) {
    this.firstName = firstName;
    }
    
    /**
    *
    * @return
    * The lastName
    */
    @JsonProperty("lastName")
    public String getLastName() {
    return lastName;
    }
    
    /**
    *
    * @param lastName
    * The lastName
    */
    @JsonProperty("lastName")
    public void setLastName(String lastName) {
    this.lastName = lastName;
    }
    
    @JsonAnyGetter
    public Map<String, Object> getAdditionalProperties() {
    return this.additionalProperties;
    }
    
    @JsonAnySetter
    public void setAdditionalProperty(String name, Object value) {
    this.additionalProperties.put(name, value);
    }
    
    }
    

    LoadFromJSON.java

    import org.codehaus.jettison.json.JSONObject;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    public class LoadFromJSON {
    
        public static void main(String args[]) throws Exception {
            JSONObject json = new JSONObject();
            json.put("id", 2);
            json.put("firstName", "hello");
            json.put("lastName", "world");
    
            byte[] jsonData = json.toString().getBytes();
    
            ObjectMapper mapper = new ObjectMapper();
            Employee employee = mapper.readValue(jsonData, Employee.class);
    
            System.out.print(employee.getLastName());
    
        }
    }
    
    0 讨论(0)
  • 2020-11-21 05:43

    Give boon a try:

    https://github.com/RichardHightower/boon

    It is wicked fast:

    https://github.com/RichardHightower/json-parsers-benchmark

    Don't take my word for it... check out the gatling benchmark.

    https://github.com/gatling/json-parsers-benchmark

    (Up to 4x is some cases, and out of the 100s of test. It also has a index overlay mode that is even faster. It is young but already has some users.)

    It can parse JSON to Maps and Lists faster than any other lib can parse to a JSON DOM and that is without Index Overlay mode. With Boon Index Overlay mode, it is even faster.

    It also has a very fast JSON lax mode and a PLIST parser mode. :) (and has a super low memory, direct from bytes mode with UTF-8 encoding on the fly).

    It also has the fastest JSON to JavaBean mode too.

    It is new, but if speed and simple API is what you are looking for, I don't think there is a faster or more minimalist API.

    0 讨论(0)
  • 2020-11-21 05:48

    What's wrong with the standard stuff?

    JSONObject jsonObject = new JSONObject(someJsonString);
    JSONArray jsonArray = jsonObject.getJSONArray("someJsonArray");
    String value = jsonArray.optJSONObject(i).getString("someJsonValue");
    
    0 讨论(0)
提交回复
热议问题