如何將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. html - angular項目中如何讓外鏈網頁在本項目中展示?2. spring-mvc - spring-session-redis HttpSessionListener失效3. 淺談Vue使用Cascader級聯選擇器數據回顯中的坑4. 運行python程序時出現“應用程序發生異常”的內存錯誤?5. java - Spring boot 讀取 放在 jar 包外的,log4j 配置文件,系統有創建日志文件,不寫入日志信息。6. IOS app應用軟件的id號怎么查詢?比如百度貼吧的app-id=4779278137. 正在使用electron和node.js做桌面應用,需要實時監聽是否有網絡連接,node或者electron是否可以做到8. node.js - 剛裝上最新node,npm install報這個錯誤!求ndoe大神解答!!!9. mysql - 查詢 修改數據庫優化問題吧10. Help!求幫助

網公網安備