如何將JSON數(shù)組轉(zhuǎn)換為Java列表。我正在使用svenson
您不能將此json轉(zhuǎn)換為,List但可以將其轉(zhuǎn)換為Map。看到你的json String:
...'Example': [{ 'foo': 'a1', 'bar': 'b1', 'fubar': 'c1'},{ 'foo': 'a2', 'bar': 'b2', 'fubar': 'c2'},...]}
試試這個(gè):
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解決方法
我試圖將多個(gè)相同類型的對象轉(zhuǎn)換為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; }...}
我希望能夠?qū)@取的json字符串轉(zhuǎn)換為Example對象列表。我想做這樣的事情:
JSONParser parser = new JSONParser();parser.addTypeHint('.Example[]',Example.class);List<Example> result = parser.parse(List.class,json);
這樣做我得到一個(gè)錯(cuò)誤:
Cannot set property Example on class java.util.ArrayList
相關(guān)文章:
1. Docker for Mac 創(chuàng)建的dnsmasq容器連不上/不工作的問題2. javascript - QWebEngineView 如何爬 angular 的動(dòng)態(tài)數(shù)據(jù)?3. javascript - 使用angular 的ui-sref 中出現(xiàn)了中文參數(shù),點(diǎn)擊跳轉(zhuǎn)后瀏覽器的地址欄里出現(xiàn)轉(zhuǎn)義后的%AE....%a%44. java - 一段遞歸代碼的問題5. java - instance method中 static后的<K>是什么意思?6. html5 - 這個(gè)代碼顯示功能如何實(shí)現(xiàn)?7. javascript - 用JS 七牛上傳圖片出現(xiàn)文件已存在的錯(cuò)誤(file exists)8. java - springboot新手學(xué)習(xí)9. css3 - 圖片等比例縮放10. java - com.android.internal.R.attr.dialogTheme 這個(gè)dialogTheme的內(nèi)容再哪里查看?
