把嵌套Json转换成Java对象

来源:互联网 发布:光纤交换机查看端口 编辑:程序博客网 时间:2024/05/29 08:38

from: https://gxnotes.com/article/20205.html

问题描述

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


解决方案

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': '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);    }}
原创粉丝点击