有人可以帮我解析这个JSON文件吗?

时间:2011-12-14 19:27:13

标签: android json parsing textview

我有这个JSON文件:

 {
    "ics_desire":{
    "version":"Beta 0.1.1",
    "description":"description here",
    "build-fingerprint":"fingerprint"
 }

现在我想将version部分放在txtVersion文本视图中,将description部分放在txtDescription文本视图中。

有人会帮助我吗?

3 个答案:

答案 0 :(得分:0)

首先说明JSON代码的格式不正确。您可以转到http://json.parser.online.fr/验证您是否正确格式化了JSON代码。 你正确的JSON如下(你错过了一个结束))

{
"ics_desire": {
    "version": "Beta 0.1.1",
    "description": "description here",
    "build-fingerprint": "fingerprint"
}
}

接下来,这是我过去用于测试的工作JSON代码的示例。

{
"HealthySubstituteData": [
    {
        "Assoc_ID": "1",
        "uFood": "White Flour",
        "hFood": "Wheat Flour",
        "Category": "Baking",
        "Description": "You can substitute blah blah blah...",
        "Count": "5",
        "submittedBy": "Administrator"
    }
]
}

这是我用来获取数据的代码。

    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
    JSONObject json = JSONfunctions.getJSONfromURL("http://your.url.com/whaterver");

    try
    {
        JSONArray  healthySubstituteData = json.getJSONArray("HealthySubstituteData");



        for(int i=0;i<healthySubstituteData.length();i++)
        {                       
            HashMap<String, String> map = new HashMap<String, String>();    
            JSONObject e = healthySubstituteData.getJSONObject(i);



            map.put("Assoc_ID", (String) e.get("Assoc_ID"));
            map.put("uFood", (String) e.get("uFood"));
            map.put("hFood", (String) e.get("hFood"));
            map.put("category", (String) e.get("Category"));
            map.put("description", (String) e.get("Description"));
            map.put("count", (String) e.get("Count"));
            map.put("submittedBy", (String) e.get("submittedBy"));
            mylist.add(map);            
        }       
    }

所以现在我最终得到了一个HashMap类型的数组列表,我可以用它做任何我想做的事。

答案 1 :(得分:0)

您可以创建一个简单的类

public class Myclass{
String version;
String description;
String build-fingerprint;
};

public class Myclass{ String version; String description; String build-fingerprint; };

然后使用Gson将json转换为您的对象,反之亦然:

Gson gson = new Gson();
Myclass obj = gson.fromJson(json_string, Myclass.class);

json_string应该包含你的jason字符串。 现在,您可以使用getter获取类对象值。

Note: Gson is an external library you need to import, download it from google.

答案 2 :(得分:0)

忽略JSON中缺少的括号,此代码可以帮助您完成

JSONObject json = JSONfunctions.getJSONfromURL("http://your.url.com/whaterver"); //the site where you get your JSON
JSONObject daata = json.getJSONObject("ics_desire"); //grabbing the inner object
String version = daata.getString("version");         //grabbing values
String description = daata.getString("description");
txtVersion.setText(version);                         //Hope you have initialized the Views.
txtDescription.setText(description);