将JSON数据转换为Java对象 [英] Converting JSON data to Java object

查看:135
本文介绍了将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对象的数组。目的是提取任何给定对象拥有包含其他JSON对象的组属性的ID列表。我将Google的Gson视为潜在的JSON插件。任何人都可以提供某种形式的指导,以了解如何从这个JSON字符串中生成Java?

解决方案


我将Google的Gson看作潜在的JSON插件。任何人都可以提供某种形式的指导,以了解如何从此JSON字符串生成Java?


Google 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':'计算和信息系统','
+''id':1,'
+''children':'true','
+' 'groups':[{
+'title':'Level 1 CIS','
+''id':2,'
+''children':'true' ,
+'groups':[{
+'title':'介绍到计算和互联网','
+''id':3,
+''children':'false','
+''groups':[]
+}]
+}]
+} ;

//现在做魔术。
Data data = new Gson()。fromJson(json,Data.class);

//显示它。
System.out.println(data);
}

}

class数据{
私有字符串标题;
私人长ID;
私人布尔儿童;
私人列表< Data>组;

public String getTitle(){return title; }
public Long getId(){return id; }
public Boolean getChildren(){return children; }
public List< Data> getGroups(){返回组; }

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; }
$ b $ public String toString(){
return String.format(title:%s,id:%d,children:%s,groups:%s,title,id,儿童,团体);
}
}

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

参见:




I want to be able to access properties from a JSON string within my Java action method. The string is available by simply saying myJsonString = object.getJson(). Below is an example of what the string can look like:

{
    'title': 'ComputingandInformationsystems',
    'id': 1,
    'children': 'true',
    'groups': [{
        'title': 'LeveloneCIS',
        'id': 2,
        'children': 'true',
        'groups': [{
            'title': 'IntroToComputingandInternet',
            'id': 3,
            'children': 'false',
            'groups': []
        }]
    }]
}

In this string every JSON object contains an array of other JSON objects. The intention is to extract a list of IDs where any given object possessing a group property that contains other JSON objects. 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?

解决方案

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 supports generics and nested beans. The [] in JSON represents an array and should map to a Java collection such as List or just a plain Java array. The {} in JSON represents an object and should map to a Java Map or just some JavaBean class.

You have a JSON object with several properties of which the groups property represents an array of nested objects of the very same type. This can be parsed with Gson the following way:

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

Fairly simple, isn't it? Just have a suitable JavaBean and call Gson#fromJson().

See also:

这篇关于将JSON数据转换为Java对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆