如何將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. Span標簽2. docker-machine添加一個已有的docker主機問題3. redis啟動有問題?4. 關docker hub上有些鏡像的tag被標記““This image has vulnerabilities””5. docker-compose中volumes的問題6. android新手一枚,android使用httclient獲取服務器端數據失敗,但是用java工程運行就可以成功獲取。7. javascript - ng-options 設置默認選項,不是設置第一個哦,看清楚了!8. angular.js使用$resource服務把數據存入mongodb的問題。9. java - Collections類里的swap函數,源碼為什么要新定義一個final的List型變量l指向傳入的list?10. css - 求推薦適用于vue2的框架 像bootstrap這種類型的
