如何将JSON数组转换为Java列表。我正在使用svenson
您不能将此json转换为,List但可以将其转换为Map。看到你的json String:
...'Example': [{ 'foo': 'a1', 'bar': 'b1', 'fubar': 'c1'},{ 'foo': 'a2', 'bar': 'b2', 'fubar': 'c2'},...]}
试试这个:
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解决方法
我试图将多个相同类型的对象转换为ListJava。例如,我的json是:
{ 'Example': [{ 'foo': 'a1','bar': 'b1','fubar': 'c1'},{ 'foo': 'a2','bar': 'b2','fubar': 'c2'},{ 'foo': 'a3','bar': 'b3','fubar': 'c3'} ]}
我有一堂课:
public class Example { private String foo; private String bar; private String fubar; public Example(){}; public void setFoo(String f){foo = f; } public void setBar(String b){bar = b; } public void setFubar(String f){fubar = f; }...}
我希望能够将获取的json字符串转换为Example对象列表。我想做这样的事情:
JSONParser parser = new JSONParser();parser.addTypeHint('.Example[]',Example.class);List<Example> result = parser.parse(List.class,json);
这样做我得到一个错误:
Cannot set property Example on class java.util.ArrayList
相关文章:
1. angular.js - Web应用,单页面应用Cache问题2. android - webview 自定义加载进度条3. position:absolute、float、display:inline-block 都能实现相同效果,区别是什么?4. android - 如何缩小APK的体积5. css3 - 这个效果用 CSS 可以实现吗?border-image6. vue.js - vue 打包后 nginx 服务端API请求跨域问题无法解决。7. docker-compose 为何找不到配置文件?8. angular.js - angular post的Content-Type被设置,导致不能上传图片,求助!!9. javascript - vue更改当前节点元素10. mac连接阿里云docker集群,已经卡了2天了,求问?

网公网安备