将JSON数据转换为Java对象

我希望能够在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对象的组属性.我把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解析:

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

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

也可以看看:

> Json.org – JSON简介
> Gson User Guide – Gson简介

上一篇:java.sql.Time异常


下一篇:Twitter使用类似twitter4j的东西将JSON字符串保存到Java对象(PO​​JO).