如何將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. javascript - JS如何取對稱范圍的隨機數?2. java - ehcache緩存用的是虛擬機內存么?3. 數據庫 - mysql如何處理數據變化中的事務?4. android - java 泛型不支持數組,那么RxJava的Map集合有什么方便的手段可以定義獲得一串共同父類集合數據呢?5. java - mongodb分片集群下,count和聚合統計問題6. 關于docker下的nginx壓力測試7. 服務器端 - 采用nginx做web服務器,C++開發應用程序 出現拒絕連接請求?8. javascript - 有什么兼容性比較好的辦法來判斷瀏覽器窗口的類型?9. dockerfile - 我用docker build的時候出現下邊問題 麻煩幫我看一下10. python - pandas按照列A和列B分組,將列C求平均數,怎樣才能生成一個列A,B,C的dataframe
