我希望能够在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 ?


当前回答

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

其他回答

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

这里有更多的好选择:

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

编辑(2013年8月/):

还有一点需要考虑:

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

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

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

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

我认为谷歌的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 -->
        <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;
    }