栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

将JSON数据转换为Java对象?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

将JSON数据转换为Java对象?

我将Google的Gson视为潜在的JSON插件。谁能提供某种形式的指导,说明如何从此JSON字符串生成Java?

Google Gson支持泛型和嵌套bean。[]JSON中的in表示一个数组,应映射到Java集合,例如List或仅映射到普通Java数组。{}JSON中的in代表一个对象,应映射到Java Map或某些JavaBean类。

你有一个带有多个属性的JSON对象,这些属性的groups属性表示同一类型的嵌套对象的数组。可以通过以下方式使用Gson进行解析:

package com.codingdict;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);    }}

也可以看看:

  • Json.org -JSON简介
  • Gson用户指南 -Gson简介


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/367988.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号