Android如何用Gson把数据转换成List
具体问题:
我现在有任意长度的json数据,用php的json_encode()生成,如下格式
[{"rowID":"1","Name":"tqtqwet","Comment":"qewrtqwe"},{"rowID":"2","Name":"waf","Comment":"agsadga"},{"rowID":"3","Name":"android","Comment":"fafdadsf"},{"rowID":"4","Name":"android222","Comment":"fasdfas"},{"rowID":"5","Name":"fadfa","Comment":"adgasd"}]
现在想用把它转换成List
解决办法:
这个json数据格式很简单,不用你想象的那么复杂就能解析;
你需要一个JavaBean对象:
CustomClass.java:
public class CustomClass { private String Name; private String Comment; public String getName() { return Name; } public void setName(String name) { Name = name; } public String getComment() { return Comment; } public void setComment(String comment) { Comment = comment; } }
MainActivity.java:
public class MainActivity extends Activity { //你的json数据 String jsonString=" [{\"rowID\":\"1\",\"Name\":\"tqtqwet\",\"Comment\":\"qewrtqwe\"},{\"rowID\":\"2\",\"Name\":\"waf\",\"Comment\":\"agsadga\"},{\"rowID\":\"3\",\"Name\":\"android\",\"Comment\":\"fafdadsf\"},{\"rowID\":\"4\",\"Name\":\"android222\",\"Comment\":\"fasdfas\"},{\"rowID\":\"5\",\"Name\":\"fadfa\",\"Comment\":\"adgasd\"}]"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Type listType = new TypeToken<ArrayList<CustomClass>>(){}.getType(); ArrayList<CustomClass> customList = new Gson().fromJson(jsonString, listType); } }
customList就是你想要的那个带有json数据的集合,你可以通过customList.get(index).getName() or getXXX()得到你想要的值
更多相关技术文章,请访问PHP中文网!