我希望能够在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文件,它将返回对象。

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

其他回答

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

import com.restfb.json.JsonObject;

...

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

etc.

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

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

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

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

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

注意,Jackson修复了这些问题,并且比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;
    }