我希望能够在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': []
        }]
    }]
}

在这个字符串中,每个JSON对象都包含一个其他JSON对象的数组。其目的是提取一个id列表,其中任何给定对象拥有包含其他JSON对象的group属性。我认为谷歌的Gson是一个潜在的JSON插件。谁能提供一些形式的指导,我如何从这个JSON字符串生成Java ?


我认为谷歌的Gson是一个潜在的JSON插件。谁能提供一些形式的指导,我如何从这个JSON字符串生成Java ?

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

您有一个带有几个属性的JSON对象,其中groups属性表示同一类型的嵌套对象数组。可以用Gson这样解析:

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

如果您使用带有特殊映射的键或值的任何类型的特殊映射,您将发现谷歌的实现并没有考虑到这一点。

当心Gson!它非常酷,非常棒,但是当你想做任何事情而不是简单的对象时,你可能很容易就需要开始构建自己的序列化器(这并不难)。

此外,如果你有一个对象数组,你反序列化一些json到该对象数组,真正的类型是LOST!完整的对象甚至不会被复制!使用XStream . .如果使用jsondriver并设置适当的设置,将把丑陋的类型编码到实际的json中,这样你就不会丢失任何东西。为真正的序列化付出了很小的代价(丑陋的json)。

注意,Jackson修复了这些问题,并且比GSON更快。

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

这里有更多的好选择:

Jackson (Github)—强大的数据绑定(JSON到/从pojo),流(超快),树模型(方便无类型访问) Flex-JSON——高度可配置的序列化

编辑(2013年8月/):

还有一点需要考虑:

Genson——类似Jackson的功能,旨在让开发人员更容易配置

如果,通过任何更改,您在一个已经使用http://restfb.com/的应用程序中,那么您可以这样做:

import com.restfb.json.JsonObject;

...

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

etc.

或者杰克逊:

String json = "...";
ObjectMapper m = new ObjectMapper();
Set<Product> products = m.readValue(json, new TypeReference<Set<Product>>() {});
HashMap keyArrayList = new HashMap();
Iterator itr = yourJson.keys();
while (itr.hasNext())
{
    String key = (String) itr.next();
    keyArrayList.put(key, yourJson.get(key).toString());
}

标准的东西有什么问题?

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

试试boon吧:

https://github.com/RichardHightower/boon

它快得出奇。

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

不要相信我的话……查看加特林基准。

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

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

它可以解析JSON到地图和列表比任何其他库可以解析到JSON DOM更快,这是没有索引覆盖模式。与Boon索引叠加模式,它甚至更快。

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

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

它是新的,但如果速度和简单的API是你所追求的,我认为没有更快或更简单的API了。

根据输入的JSON格式(字符串/文件)创建一个jSONString。JSON对应的Message类对象示例如下:

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

简单和工作的java代码转换JSONObject到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

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

    }
}

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

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文件,它将返回对象。

File file = new File("D:\\Coding\\tickets\\temp.json");
ObjectMapper om = new ObjectMapper();
Profile profile = om.readValue(file, new TypeReference<Profile>() {});

        <!-- GSON -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.7</version>
        </dependency>
  @Test
    void readListJsonFromFileTest() throws IOException {

        Type type = new TypeToken<List<SimplePojo>>(){}.getType();

        String fromJsonFile = readFromJsonFile("json/simplePojoJsonList.json");

        List<SimplePojo> pojoList = gson.fromJson(fromJsonFile, type);

        Assertions.assertNotNull(pojoList);
    }

    @Test
    void readJsonFromFileTest() throws IOException {

        Type type = new TypeToken<SimplePojo>(){}.getType();

        String fromJsonFile = readFromJsonFile("json/simplePojoJson.json");

        SimplePojo simplePojo = gson.fromJson(fromJsonFile, type);

        Assertions.assertNotNull(simplePojo);
    }

     String readFromJsonFile(String pathToJson) throws IOException {

        InputStream resource = new ClassPathResource(pathToJson).getInputStream();

        String json = StreamUtils.copyToString(resource, StandardCharsets.UTF_8);

        return json;
    }