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

如何将JSON数组转换为Java列表。我正在使用svenson

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

如何将JSON数组转换为Java列表。我正在使用svenson

您不能将此json转换为,

List
但可以将其转换为
Map

看到你的json
String

..."Example": [        { "foo": "a1", "bar": "b1", "fubar": "c1"        },        { "foo": "a2", "bar": "b2", "fubar": "c2"        },        ...]}

在此,“ Example”是键(字符串),值是Example的List对象。

试试这个:

 parser.addTypeHint("Example[]", Example.class); Map<String,List<Example>> result1 = parser.parse(Map.class, json); for (Entry<String, List<Example>> entry : result1.entrySet()) {     for (Example example : entry.getValue()) {          System.out.println("VALUE :->"+ example.getFoo());     } }

的完整代码

Example

import java.util.List;import java.util.Map;import java.util.Map.Entry;import org.svenson.JSONParser;public class Test {    public static void main(String[] args) {        JSonParser parser = new JSonParser();        parser.addTypeHint(".Example[]", Example.class);        String json = "{" + ""Example": [" + "{" + ""foo": "a1","     + ""bar": "b1"," + ""fubar": "c1"" + "}," + "{"     + ""foo": "a2"," + ""bar": "b2"," + ""fubar": "c2""     + "}," + "{" + ""foo": "a3"," + ""bar": "b3","     + ""fubar": "c3"" + "}" + "]" + "}"";        parser.addTypeHint("Example[]", Example.class);        Map<String, List<Example>> result1 = parser.parse(Map.class, json);        for (Entry<String, List<Example>> entry : result1.entrySet()) { for (Example example : entry.getValue()) {     System.out.println("VALUE :->" + example.getFoo()); }        }    }}public class Example {    private String foo;    private String bar;    private String fubar;    public Example(){}    public void setFoo(String foo) {        this.foo = foo;    }    public String getFoo() {        return foo;    }    public void setBar(String bar) {        this.bar = bar;    }    public String getBar() {        return bar;    }    public void setFubar(String fubar) {        this.fubar = fubar;    }    public String getFubar() {        return fubar;    }}

输出

VALUE :->a1VALUE :->a2VALUE :->a3


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

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

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