将JSON数据转换为Java对象。

时间:2022-08-30 10:37:36

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(). Below is an example of what the string can look like:

我希望能够在Java操作方法中从JSON字符串访问属性。只需简单地说myJsonString = object.getJson()即可获得该字符串。下面是这个字符串的示例:

{
    'title': 'ComputingandInformationsystems',
    'id': 1,
    'children': 'true',
    'groups': [{
        'title': 'LeveloneCIS',
        'id': 2,
        'children': 'true',
        'groups': [{
            'title': 'IntroToComputingandInternet',
            'id': 3,
            'children': 'false',
            'groups': []
        }]
    }]
}

In this string every JSON object contains an array of other JSON objects. The intention is to extract a list of IDs where any given object possessing a group property that contains other JSON objects. I looked at Google's Gson as a potential JSON plugin. Can anyone offer some form of guidance as to how I can generate Java from this JSON string?

在这个字符串中,每个JSON对象包含一个其他JSON对象数组。其目的是提取一个id列表,其中任何给定对象拥有包含其他JSON对象的组属性。我把谷歌的Gson看作一个潜在的JSON插件。对于如何从JSON字符串生成Java,任何人都可以提供某种形式的指导吗?

11 个解决方案

#1


293  

I looked at Google's Gson as a potential JSON plugin. Can anyone offer some form of guidance as to how I can generate Java from this JSON string?

我把谷歌的Gson看作一个潜在的JSON插件。对于如何从JSON字符串生成Java,任何人都可以提供某种形式的指导吗?

Google Gson supports generics and nested beans. The [] in JSON represents an array and should map to a Java collection such as List or just a plain Java array. The {} in JSON represents an object and should map to a Java Map or just some JavaBean class.

谷歌Gson支持泛型和嵌套bean。JSON表示一个数组,应该映射到一个Java集合,比如List或者一个普通的Java数组。JSON表示一个对象,应该映射到Java映射或者只是一些JavaBean类。

You have a JSON object with several properties of which the groups property represents an array of nested objects of the very same type. This can be parsed with Gson the following way:

您有一个JSON对象,它具有多个属性,其中组属性表示同一类型的嵌套对象数组。可以通过以下方式与Gson解析:

package com.*.q1688099;

import java.util.List;
import com.google.gson.Gson;

public class Test {

    public static void main(String... args) throws Exception {
        String json = 
            "{"
                + "'title': 'Computing and Information systems',"
                + "'id' : 1,"
                + "'children' : 'true',"
                + "'groups' : [{"
                    + "'title' : 'Level one CIS',"
                    + "'id' : 2,"
                    + "'children' : 'true',"
                    + "'groups' : [{"
                        + "'title' : 'Intro To Computing and Internet',"
                        + "'id' : 3,"
                        + "'children': 'false',"
                        + "'groups':[]"
                    + "}]" 
                + "}]"
            + "}";

        // Now do the magic.
        Data data = new Gson().fromJson(json, Data.class);

        // Show it.
        System.out.println(data);
    }

}

class Data {
    private String title;
    private Long id;
    private Boolean children;
    private List<Data> groups;

    public String getTitle() { return title; }
    public Long getId() { return id; }
    public Boolean getChildren() { return children; }
    public List<Data> getGroups() { return groups; }

    public void setTitle(String title) { this.title = title; }
    public void setId(Long id) { this.id = id; }
    public void setChildren(Boolean children) { this.children = children; }
    public void setGroups(List<Data> groups) { this.groups = groups; }

    public String toString() {
        return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
    }
}

Fairly simple, isn't it? Just have a suitable JavaBean and call Gson#fromJson().

很简单,不是吗?只要有一个合适的JavaBean,并调用Gson#fromJson()。

See also:

  • Json.org - Introduction to JSON
  • Json.org - JSON简介。
  • Gson User Guide - Introduction to Gson
  • Gson用户指南- Gson介绍。

#2


42  

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).

Bewaaaaare Gson !它非常酷,非常好,但是第二个您想要做的除了简单的对象之外,您可以很容易地需要开始构建自己的序列化器(这并不困难)。

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.

另外,如果您有一个对象数组,并且将一些json反序列化到该对象数组中,那么真正的类型就会丢失!所有的对象都不会被复制!使用XStream . .如果使用jsondriver并设置适当的设置,将会将难看的类型编码到实际的json中,这样就不会释放任何东西。用于真正序列化的一个小代价(丑陋的json)。

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

请注意,Jackson解决了这些问题,并且比GSON更快。

#3


23  

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

奇怪的是,迄今为止提到的唯一像样的JSON处理器是GSON。

Here are more good choices:

这里有更多更好的选择:

  • Jackson (Github) -- powerful data binding (JSON to/from POJOs), streaming (ultra fast), tree model (convenient for untyped access)
  • Jackson (Github)——强大的数据绑定(JSON到/来自pojo),流(超快),树模型(方便非类型访问)
  • Flex-JSON -- highly configurable serialization
  • Flex-JSON——高度可配置的序列化。

EDIT (Aug/2013):

编辑(2013年8月/):

One more to consider:

一个考虑:

  • Genson -- functionality similar to Jackson, aimed to be easier to configure by developer
  • Genson——类似于Jackson的功能,旨在更容易地由开发人员配置。

#4


11  

Or with Jackson:

或与杰克逊:

String json = "...
ObjectMapper m = new ObjectMapper();
Set<Product> products = m.readValue(json, new TypeReference<Set<Product>>() {});

#5


4  

If, by any change, you are in an application which already uses http://restfb.com/ then you can do:

如果您的应用程序已经使用了http://restfb.com/,那么您可以这样做:

import com.restfb.json.JsonObject;

...

JsonObject json = new JsonObject(jsonString);
json.get("title");

etc.

等。

#6


2  

If you use any kind of special maps with keys or values also of special maps, you will find it's not contemplated by the implementation of google.

如果您使用任何特殊的带有键或值的特殊地图,您会发现它并不是由谷歌的实现所考虑的。

#7


2  

HashMap keyArrayList = new HashMap();
        Iterator itr = yourJson.keys();
        while (itr.hasNext())
        {
            String key =(String) itr.next();
            keyArrayList.put(key, yourJson.get(key).toString());
        }

#8


1  

What's wrong with the standard stuff?

标准的东西有什么问题?

JSONObject jsonObject = new JSONObject(someJsonString);
JSONArray jsonArray = jsonObject.getJSONArray("someJsonArray");
String value = jsonArray.optJSONObject(i).getString("someJsonValue");

#9


1  

Easy and working java code to convert JSONObject to Java Object

Employee.java

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

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());

    }
}

#10


0  

Give boon a try:

给恩一试:

https://github.com/RichardHightower/boon

https://github.com/RichardHightower/boon

It is wicked fast:

这是邪恶的快:

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

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

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

不要相信我的话……看看gatling基准测试。

https://github.com/gatling/json-parsers-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.)

(最多是4倍,在100次测试中。它还有一个更快的索引覆盖模式。它很年轻,但已经有了一些用户。

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.

它可以将JSON解析为映射和列表,比任何其他lib都能解析到JSON DOM,而且没有索引覆盖模式。使用Boon索引覆盖模式,它甚至更快。

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).

它还有一个非常快的JSON松散模式和一个PLIST解析器模式。(并且拥有超级低的内存,直接从字节模式和UTF-8编码在飞行中)。

It also has the fastest JSON to JavaBean mode too.

它也有最快的JSON到JavaBean模式。

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.

它是新的,但是如果速度和简单的API是您正在寻找的,我不认为有一个更快或更简单的API。

#11


0  

Depending on the input JSON format(string/file) create a jSONString. Sample Message class object corresponding to JSON can be obtained as below:

根据输入JSON格式(字符串/文件)创建jSONString。与JSON对应的示例消息类对象可获得如下:

Message msgFromJSON = new ObjectMapper().readValue(jSONString, Message.class);

消息msgFromJSON = new ObjectMapper()。readValue(jSONString Message.class);

#1


293  

I looked at Google's Gson as a potential JSON plugin. Can anyone offer some form of guidance as to how I can generate Java from this JSON string?

我把谷歌的Gson看作一个潜在的JSON插件。对于如何从JSON字符串生成Java,任何人都可以提供某种形式的指导吗?

Google Gson supports generics and nested beans. The [] in JSON represents an array and should map to a Java collection such as List or just a plain Java array. The {} in JSON represents an object and should map to a Java Map or just some JavaBean class.

谷歌Gson支持泛型和嵌套bean。JSON表示一个数组,应该映射到一个Java集合,比如List或者一个普通的Java数组。JSON表示一个对象,应该映射到Java映射或者只是一些JavaBean类。

You have a JSON object with several properties of which the groups property represents an array of nested objects of the very same type. This can be parsed with Gson the following way:

您有一个JSON对象,它具有多个属性,其中组属性表示同一类型的嵌套对象数组。可以通过以下方式与Gson解析:

package com.*.q1688099;

import java.util.List;
import com.google.gson.Gson;

public class Test {

    public static void main(String... args) throws Exception {
        String json = 
            "{"
                + "'title': 'Computing and Information systems',"
                + "'id' : 1,"
                + "'children' : 'true',"
                + "'groups' : [{"
                    + "'title' : 'Level one CIS',"
                    + "'id' : 2,"
                    + "'children' : 'true',"
                    + "'groups' : [{"
                        + "'title' : 'Intro To Computing and Internet',"
                        + "'id' : 3,"
                        + "'children': 'false',"
                        + "'groups':[]"
                    + "}]" 
                + "}]"
            + "}";

        // Now do the magic.
        Data data = new Gson().fromJson(json, Data.class);

        // Show it.
        System.out.println(data);
    }

}

class Data {
    private String title;
    private Long id;
    private Boolean children;
    private List<Data> groups;

    public String getTitle() { return title; }
    public Long getId() { return id; }
    public Boolean getChildren() { return children; }
    public List<Data> getGroups() { return groups; }

    public void setTitle(String title) { this.title = title; }
    public void setId(Long id) { this.id = id; }
    public void setChildren(Boolean children) { this.children = children; }
    public void setGroups(List<Data> groups) { this.groups = groups; }

    public String toString() {
        return String.format("title:%s,id:%d,children:%s,groups:%s", title, id, children, groups);
    }
}

Fairly simple, isn't it? Just have a suitable JavaBean and call Gson#fromJson().

很简单,不是吗?只要有一个合适的JavaBean,并调用Gson#fromJson()。

See also:

  • Json.org - Introduction to JSON
  • Json.org - JSON简介。
  • Gson User Guide - Introduction to Gson
  • Gson用户指南- Gson介绍。

#2


42  

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).

Bewaaaaare Gson !它非常酷,非常好,但是第二个您想要做的除了简单的对象之外,您可以很容易地需要开始构建自己的序列化器(这并不困难)。

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.

另外,如果您有一个对象数组,并且将一些json反序列化到该对象数组中,那么真正的类型就会丢失!所有的对象都不会被复制!使用XStream . .如果使用jsondriver并设置适当的设置,将会将难看的类型编码到实际的json中,这样就不会释放任何东西。用于真正序列化的一个小代价(丑陋的json)。

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

请注意,Jackson解决了这些问题,并且比GSON更快。

#3


23  

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

奇怪的是,迄今为止提到的唯一像样的JSON处理器是GSON。

Here are more good choices:

这里有更多更好的选择:

  • Jackson (Github) -- powerful data binding (JSON to/from POJOs), streaming (ultra fast), tree model (convenient for untyped access)
  • Jackson (Github)——强大的数据绑定(JSON到/来自pojo),流(超快),树模型(方便非类型访问)
  • Flex-JSON -- highly configurable serialization
  • Flex-JSON——高度可配置的序列化。

EDIT (Aug/2013):

编辑(2013年8月/):

One more to consider:

一个考虑:

  • Genson -- functionality similar to Jackson, aimed to be easier to configure by developer
  • Genson——类似于Jackson的功能,旨在更容易地由开发人员配置。

#4


11  

Or with Jackson:

或与杰克逊:

String json = "...
ObjectMapper m = new ObjectMapper();
Set<Product> products = m.readValue(json, new TypeReference<Set<Product>>() {});

#5


4  

If, by any change, you are in an application which already uses http://restfb.com/ then you can do:

如果您的应用程序已经使用了http://restfb.com/,那么您可以这样做:

import com.restfb.json.JsonObject;

...

JsonObject json = new JsonObject(jsonString);
json.get("title");

etc.

等。

#6


2  

If you use any kind of special maps with keys or values also of special maps, you will find it's not contemplated by the implementation of google.

如果您使用任何特殊的带有键或值的特殊地图,您会发现它并不是由谷歌的实现所考虑的。

#7


2  

HashMap keyArrayList = new HashMap();
        Iterator itr = yourJson.keys();
        while (itr.hasNext())
        {
            String key =(String) itr.next();
            keyArrayList.put(key, yourJson.get(key).toString());
        }

#8


1  

What's wrong with the standard stuff?

标准的东西有什么问题?

JSONObject jsonObject = new JSONObject(someJsonString);
JSONArray jsonArray = jsonObject.getJSONArray("someJsonArray");
String value = jsonArray.optJSONObject(i).getString("someJsonValue");

#9


1  

Easy and working java code to convert JSONObject to Java Object

Employee.java

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

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());

    }
}

#10


0  

Give boon a try:

给恩一试:

https://github.com/RichardHightower/boon

https://github.com/RichardHightower/boon

It is wicked fast:

这是邪恶的快:

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

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

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

不要相信我的话……看看gatling基准测试。

https://github.com/gatling/json-parsers-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.)

(最多是4倍,在100次测试中。它还有一个更快的索引覆盖模式。它很年轻,但已经有了一些用户。

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.

它可以将JSON解析为映射和列表,比任何其他lib都能解析到JSON DOM,而且没有索引覆盖模式。使用Boon索引覆盖模式,它甚至更快。

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).

它还有一个非常快的JSON松散模式和一个PLIST解析器模式。(并且拥有超级低的内存,直接从字节模式和UTF-8编码在飞行中)。

It also has the fastest JSON to JavaBean mode too.

它也有最快的JSON到JavaBean模式。

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.

它是新的,但是如果速度和简单的API是您正在寻找的,我不认为有一个更快或更简单的API。

#11


0  

Depending on the input JSON format(string/file) create a jSONString. Sample Message class object corresponding to JSON can be obtained as below:

根据输入JSON格式(字符串/文件)创建jSONString。与JSON对应的示例消息类对象可获得如下:

Message msgFromJSON = new ObjectMapper().readValue(jSONString, Message.class);

消息msgFromJSON = new ObjectMapper()。readValue(jSONString Message.class);