如何解析json类似的内部对象?

时间:2012-08-30 18:13:15

标签: android json parsing

我有以下代码

{"sports" :[{"name" :"baseball","id" :1,"links" :{"api" :{"sports" :{"href" :"http://api.espn.com/v1/sports/baseball"},"news" :{"href" :"http://api.espn.com/v1/sports/baseball/news"},"notes" :{"href" :"http://api.espn.com/v1/sports/baseball/news/notes"},"headlines" :{"href" :"http://api.espn.com/v1/sports/baseball/news/headlines"},"events" :{"href" :"http://api.espn.com/v1/sports/baseball/events"}}},"leagues" :[{"name" :"Major League Baseball","abbreviation" :"mlb","id" :10,"groupId" :9,"shortName" :"MLB","season" :{"year" :2012,"type" :2,"description" :"regular","startDate" :"2012-03-27T19:00:00Z","endDate" :"2012-10-05T06:59:59Z"},"week" :{"number" :23,"startDate" :"2012-08-28T19:00:00Z","endDate" :"2012-09-04T18:59:00Z"}}]}],"timestamp" :"2012-08-30T18:01:29Z","status" :"success"}

我想解析json对象,在sports对象中我们有另一个运动对象如何用元素数组解析内部json对象。

我正在尝试使用以下代码:

public class BaseballActivity extends ListActivity{

private static String url = "http://api.espn.com/v1/sports/baseball?apikey=h29yphwtf7893hktfbn7cd5g";

private static final String TAG_SPORTS = "sports";
private static final String TAG_ID = "id";
private static final String TAG_TIMESTAMP = "timestamp";
private static final String TAG_NAME = "name";
private static final String TAG_NEWS = "news";
private static final String TAG_HEADLINES = "headlines";
private static final String TAG_LINKS = "links";
private static final String TAG_API = "api";
private static final String TAG_SPORTS1 = "sports";
private static final String TAG_HREF = "href";

JSONArray sports = null;

@Override
public void onCreate(Bundle savedInstanceState) {


    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    // HashMap for ListView

    ArrayList<HashMap<String, String>> sportsList = new ArrayList<HashMap<String, String>>();

    // creating Json parser instance
    JSONParser jParser = new JSONParser();

    // getting Json String from url

    JSONObject json = jParser.getJSONFromUrl(url);

    try{
        // Getting Array of Contacts
                    sports = json.getJSONArray(TAG_SPORTS);

                    // looping through All Contacts
                    for(int i = 0; i < sports.length(); i++){
                        JSONObject c = sports.getJSONObject(i);


            //String news = c.getString(TAG_NEWS);
           // String headlines = c.getString(TAG_HEADLINES);
            String name = c.getString(TAG_NAME);
           // String timestamp = c.getString(TAG_TIMESTAMP);
            String id = c.getString(TAG_ID);

         //   JSONObject links = c.getJSONObject(TAG_LINKS);
          //  JSONObject api = c.getJSONObject(TAG_API);
          //  JSONObject sports = c.getJSONObject(TAG_SPORTS1);

         //   String href = c.getString(TAG_HREF);



            HashMap<String, String> map = new HashMap<String, String>();

         //  map.put(TAG_TIMESTAMP, timestamp);
            map.put(TAG_NAME, name);
           // map.put(TAG_NEWS, news);
           // map.put(TAG_HEADLINES, headlines);
            map.put(TAG_ID, id);
         //   map.put(TAG_HREF, href);
            sportsList.add(map);
         }
    }
        catch (JSONException e) {
            e.printStackTrace();    

        }


    ListAdapter adapter = new SimpleAdapter(this, sportsList,
            R.layout.list_item,
            new String[]{TAG_NAME,TAG_ID} , new int[] {
            R.id.id,R.id.name});

setListAdapter(adapter);
}}



ublic class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();           

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;
}}

当我尝试解析内部对象没有输出时,可以显示名称和ID请帮帮我。

1 个答案:

答案 0 :(得分:1)

你应该有一个具有JSON字符串上的对象的类Sports

这应该为你做的工作

JSONObject jObject = new JSONObject(json); jObject.getJSONObject( “体育”);

这会使JSONOBJECT超出你的JsonString 比你将使用Googles Gson库做以下

Gson gson = new Gson(); Sports sports = gson.fromJson(jObject.toString(),Sports.class);

我建议你有一个班级来处理所有的WebReqeuisitions而不是在你的Activity上有这个代码使你的项目更有条理,你的代码会更清洁