Android parse JSONObject

2019-01-17 01:57发布

I've got a little problem with parsing json into my android app.

This is how my json file looks like:

{
"internalName": "jerry91",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
}

As You can see this structure is a little bit weird. I dont know how to read that data in my app. As I noticed those are all Objects not arrays :/

7条回答
Deceive 欺骗
2楼-- · 2019-01-17 02:43

This part do in onBackground in AsyncTask

  JSONParser jParser = new JSONParser();
 JSONObject json = jParser.getJSONFromUrl(url);


        try {

            result = json.getString("internalName");
                            data=json.getString("dataVersion");
                      ect..


        } catch (JSONException e) {
            e.printStackTrace();
        }

JsonParser

 public 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, "utf-8"), 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;

}
  }
查看更多
登录 后发表回答