将JSON数据转换为Java对象

Converting JSON data to Java object

我希望能够从Java操作方法中的JSON字符串访问属性。 只需说出myJsonString = object.getJson(),即可使用该字符串。 以下是该字符串的示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
    'title': 'ComputingandInformationsystems',
    'id': 1,
    'children': 'true',
    'groups': [{
        'title': 'LeveloneCIS',
        'id': 2,
        'children': 'true',
        'groups': [{
            'title': 'IntroToComputingandInternet',
            'id': 3,
            'children': 'false',
            'groups': []
        }]
    }]
}

在此字符串中,每个JSON对象都包含其他JSON对象的数组。 目的是提取ID列表,其中任何给定对象都具有包含其他JSON对象的group属性。 我将Google的Gson视为潜在的JSON插件。 谁能提供某种形式的指导,说明如何从此JSON字符串生成Java?


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?

Google Gson支持泛型和嵌套bean。 JSON中的[]表示一个数组,应映射到Java集合(例如List)或仅映射到纯Java数组。 JSON中的{}表示一个对象,应映射到Java Map或某些JavaBean类。

您有一个具有多个属性的JSON对象,其中的groups属性表示一组类型完全相同的嵌套对象。可以通过以下方式使用Gson进行解析:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.stackoverflow.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);
    }
}

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

也可以看看:

  • Json.org-JSON简介
  • Gson用户指南-Gson简介


格森的Bewaaaaare!这非常酷,非常棒,但是第二个您想做除简单对象以外的任何事情,您可能很容易需要开始构建自己的序列化器(这并不难)。

同样,如果您有一个对象数组,并且将一些json反序列化为该对象数组,则真正的类型是LOST!完整的对象甚至都不会被复制!使用XStream。如果使用jsondriver并设置正确的设置,它将把丑陋的类型编码为实际的json,这样您就不会丢失任何内容。真正的序列化需要支付一小笔费用(丑陋的json)。

请注意,杰克逊解决了这些问题,并且比GSON快。


奇怪的是,到目前为止提到的唯一不错的JSON处理器就是GSON。

这里有更多不错的选择:

  • 杰克逊(Github)-强大的数据绑定(与POJO之间的JSON),流式传输(超快速),树模型(方便进行无类型访问)
  • Flex-JSON-高度可配置的序列化

编辑(2013年8月):

还有一个要考虑的问题:

  • Genson-与Jackson相似的功能,旨在使开发人员更易于配置

或与杰克逊:

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


如果经过任何更改,如果您在已经使用http://restfb.com/的应用程序中,则可以执行以下操作:

1
2
3
4
5
6
import com.restfb.json.JsonObject;

...

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

等等


简单易用的Java代码将JSONObject转换为Java Object

Employee.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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());

    }
}


1
2
3
4
5
6
7
HashMap keyArrayList = new HashMap();
Iterator itr = yourJson.keys();
while (itr.hasNext())
{
    String key = (String) itr.next();
    keyArrayList.put(key, yourJson.get(key).toString());
}

如果您同时使用带有键或值的特殊地图以及特殊地图的值,您会发现Google的实现未考虑到它。


标准的东西怎么了?

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


最简单的方法是,您可以使用此softconvertvalue方法,这是一个自定义方法,您可以在其中将jsonData转换为特定的Dto类。

1
2
3
4
5
6
7
8
9
10
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);
}

根据输入的JSON格式(字符串/文件)创建一个jSONString。可以通过以下方式获取与JSON相对应的示例Message类对象:

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


试试看:

https://github.com/RichardHightower/boon

它是邪恶的:

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

不要相信我的话...查看性能指标基准。

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

(在某些情况下,高达100倍于4倍,并且在100多个测试中。它的索引覆盖模式甚至更快。它虽然很年轻,但已经有一些用户。)

它可以比其他任何库解析JSON DOM更快地解析JSON到Maps and Lists,并且没有索引覆盖模式。使用Boon Index Overlay模式,它甚至更快。

它还具有非常快速的JSON lax模式和PLIST解析器模式。 :)(并且具有超低内存,直接从字节模式直接??使用UTF-8编码)。

它还具有最快的JSON到JavaBean模式。

它是新的,但是如果您要寻找快速简单的API,那么我认为没有更快或更简单的API。