解析Android中的JSON [英] parse json in android
本文介绍了解析Android中的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:结果
JSON解析Android中
块引用>当我发现我需要使用GSON类来解析JSON到Java对象机器人。这是很容易解析简单varables或数组,但我不知道如何分析更复杂的JSON字符串,我的JSON是这样的:
{selected_id:3,数据:[{ID:3,分数:1534},{ID:1 ,得分:1234}]}
谁能帮我如何做到这一点?
解决方案// Model类 类模型{ 私人字符串MID;
私人字符串mScore; 公共模型(ID字符串,字符串分数){ MID = ID;
mScore =得分
}
// getter和setter }//在你的类
私人ArrayLsit getLsit(字符串str){
ArrayLsit<模型与GT;名单=新ArrayLsit<模型与GT;(); // URL从获取JSON字符串
JSONObject的JSON =新的JSONObject(STR); 尝试{
//获取联系人的数组
接触= json.getJSONArray(数据); //通过所有联系人循环
的for(int i = 0; I< contacts.length();我++){
JSONObject的C = contacts.getJSONObject(I) //存储在变量中的每个JSON项目
字符串ID = c.getString(ID);
串得分= c.getString(得分);
list.add(新型号(ID,分数)) }
}赶上(JSONException E){
e.printStackTrace();
} 返回目录 }Possible Duplicate:
JSON Parsing in AndroidAs I find out I need to use Gson class to parse json to Java object in android. It's quite easy to parse simple varables or array, but I don't know how to parse more complex json string, my json look like this:
{"selected_id":3, "data":[{"id":"3","score":"1534"},{"id":"1","score":"1234"}]}
Can anyone help me how to do this?
解决方案//Model class class Model { private String mId ; private String mScore; public Model (String id , String score){ mId = id ; mScore= score } //getter and setter }
// in your class
private ArrayLsit getLsit(String str){ ArrayLsit<Model > list = new ArrayLsit<Model>(); // getting JSON string from URL JSONObject json = new JSONObject(str); try { // Getting Array of Contacts contacts = json.getJSONArray("data"); // looping through All Contacts for(int i = 0; i < contacts.length(); i++){ JSONObject c = contacts.getJSONObject(i); // Storing each json item in variable String id = c.getString("id"); String score= c.getString("score"); list.add(new Model(id ,score)) } } catch (JSONException e) { e.printStackTrace(); } return list }
这篇关于解析Android中的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文