Android解析JSON

來源:互聯網
上載者:User

android架構已經為我們整合瞭解析json的包
先一個簡單的例子,json直接寫在string中
Java代碼
String staticObject = "{\"firstname\":\"Steve\",\"lastname\":\"Jobs\",\"cellphones\":\"0\"}";  
void buildObject()  
{  
    try  
    {  
        obj = new JSONObject(staticObject);  
        String x = obj.get("firstname").toString() + " " + obj.get("lastname").toString() + " has " + obj.getInt("cellphones") + " Android phones.";  
        setStatus(x);  
    }  
    catch (JSONException je)  
    {  
        setStatus("Error occured " + je.getMessage());  
    }  
}  
void setStatus(String x)  
{  
    TextView tv = (TextView) findViewById(R.id.txtStatus);  
    tv.setText(x);  
}  
String staticObject = "{\"firstname\":\"Steve\",\"lastname\":\"Jobs\",\"cellphones\":\"0\"}";  void buildObject() {  try  {   obj = new JSONObject(staticObject);   String x = obj.get("firstname").toString() + " " + obj.get("lastname").toString() + " has " + obj.getInt("cellphones") + " Android phones.";   setStatus(x);  }  catch (JSONException je)  {   setStatus("Error occured " + je.getMessage());  } }  void setStatus(String x) {  TextView tv = (TextView) findViewById(R.id.txtStatus);  tv.setText(x); }
將json寫在檔案中,並放在raw目錄下
json形式為
Java代碼
{  
"firstname":"Richard",  
"lastname":"Stearns",  
"almamater":"Cornell University",  
"occupation":"President, World Vision",  
"interview":  
    {  
        "source" : "http://blog.guykawasaki.com/2007/05/ten_or_so_quest.html#ixzz0giEIX0zY",  
        "questions":  
            [  
            {  
            "Question": "How much money does World Vision raise every year?",  
            "Answer": "Worldwide, World Vision raises about $2 billion annually; the U.S. office, which I head up, raises about half of the total."  
            },  
            {  
            "Question": "Is this the 80/20 rule where twenty percent of the people send in eighty percent of the money or are donations more spread out?",  
            "Answer": "World Vision's strength is that we are supported by hundreds of thousands of faithful people who give us about a dollar a day by sponsoring children. Our \"major donors\" account for less than five percent of our total income. Also, for a non-profit, we have quite a diversified portfolio of revenue. Just over forty percent is cash from private citizens; thirty percent is government grants in food and cash; and about thirty percent are products donated from corporation--what we call \"gifts-in-kind.\""  
            }  
            ]  
    }  
}  
{ "firstname":"Richard", "lastname":"Stearns", "almamater":"Cornell University", "occupation":"President, World Vision", "interview":  {   "source" : "http://blog.guykawasaki.com/2007/05/ten_or_so_quest.html#ixzz0giEIX0zY",   "questions":    [    {    "Question": "How much money does World Vision raise every year?",    "Answer": "Worldwide, World Vision raises about $2 billion annually; the U.S. office, which I head up, raises about half of the total."    },    {    "Question": "Is this the 80/20 rule where twenty percent of the people send in eighty percent of the money or are donations more spread out?",    "Answer": "World Vision's strength is that we are supported by hundreds of thousands of faithful people who give us about a dollar a day by sponsoring children. Our \"major donors\" account for less than five percent of our total income. Also, for a non-profit, we have quite a diversified portfolio of revenue. Just over forty percent is cash from private citizens; thirty percent is government grants in food and cash; and about thirty percent are products donated from corporation--what we call \"gifts-in-kind.\""    }    ]  } }
其中解析代碼為
Java代碼
void buildObjectFromFile()  
{  
    try  
    {  
        String x = "";  
        InputStream is = this.getResources().openRawResource(R.raw.interview);  
        byte [] buffer = new byte[is.available()];  
        while (is.read(buffer) != -1);  
        String json = new String(buffer);  
        obj = new JSONObject(json);  
        x = obj.getString("firstname") + " " + obj.getString("lastname") + "n";  
        x += obj.getString("occupation") + "n";  
        JSONObject interview =  obj.getJSONObject("interview");  
        x += "Interview source:" + interview.getString("source")  + "n";  
        JSONArray questions = interview.getJSONArray("questions");  
        x += "Number of questions: " + questions.length()  + "nn";  
        int i;  
        for (i=0;i<questions.length();i++)  
        {  
            JSONObject qa = questions.getJSONObject(i);  
            x += "------------n";  
            x += "Q" + (i+1) + ". " + qa.getString("Question") + "nn";  
            x += "A" + (i+1) + ". " + qa.getString("Answer") + "n";  
        }  
        setStatus(x);  
    }  
    catch (Exception je)  
    {  
        setStatus("Error w/file: " + je.getMessage());  
    }  

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.