如何將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. 查詢mysql數據庫中指定表指定日期的數據?有詳細2. mysql - 怎么生成這個sql表?3. mysql儲存json錯誤4. php - 公眾號文章底部的小程序二維碼如何統計?5. mysql - 表名稱前綴到底有啥用?6. mysql - 數據庫表中,兩個表互為外鍵參考如何解決7. Navicat for mysql 中以json格式儲存的數據存在大量反斜杠,如何去除?8. 在mybatis使用mysql的ON DUPLICATE KEY UPDATE語法實現存在即更新應該使用哪個標簽?9. mysql - 數據庫建字段,默認值空和empty string有什么區別 11010. sql語句 - 如何在mysql中批量添加用戶?
