开发者

JSON parsed data not displaying in android textview

I have a json encoded message which is generated by a php file. The problem is I cannot form it in a textview to show it on android.

package com.saki.json;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import org.json.JSONObject;
import org.json.JSONException;

public class JsonActivity extends Activity {
private static final String JSON_STRING =
    "{\"person\":{\"name\":\"A\",\"age\":30,\"children\":[{\"name\":\"B\",\"age\":5}," + "\"name\":\"C\",\"age\":7},{\"name\":\"D\",\"age\":9}]}}";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    TextView line1 = (TextView)findViewById(R.id.line1);
    TextView line2 = (TextView)findViewById(R.id.line2);
    TextView line3 = (TextView)findViewById(R.id.line3);
    try {
        JSONObject person = (new 开发者_如何学GoJSONObject(JSON_STRING)).getJSONObject("person");
        String name = person.getString("name");
        line1.setText("This person's name is " + name);
        line2.setText(name + " is " + person.getInt("age") + " years old.");
        line3.setText(name + " has " + person.getJSONArray("children").length()
            + " children.");
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

How can I solve this problem?


As Alex says, the JSON is formatted properly. I always run mine through http://jsonformatter.curiousconcept.com/ or http://json.parser.online.fr/ before using it. Try this:

{\"person\":{\"name\":\"A\",\"age\":30,\"children\":[{\"name\":\"B\",\"age\":5},{\"name\":\"C\",\"age\":7},{\"name\":\"D\",\"age\":9}]}}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜