仅解析json对象

时间:2013-10-28 03:12:26

标签: android json eclipse parsing

enter image description here我遇到了很多麻烦。我有一个我已解析的json数组,效果很好。我有一个我想要解析的单个用户的另一个网页。这是php。它的有效json。

{
    "userURL": "http://forum.example.com.php?u=426561",
    "userId": "426561",
    "forumName": "example name",
    "totalPosts": "19787",
    "postsPerDay": "8.11",
    "totalThanks": "40585",
    "joinDate": "2007-02-20",
    "yearsJoined": "6",
    "referrals": "17",
    "friendCount": "61",
    "recognizedDeveloper": "1",
    "recognizedContributor": "0",
    "recognizedThemer": "0",
    "moderator": "0",
    "recognizedEliteDeveloper": "0",
    "romCount": "100",
    "kernelCount": "1",
    "tutorialCount": "0",
    "modCount": "21",
    "themeCount": "0",
    "originalAppCount": "0",
    "toolkitCount": "0",
    "scriptCount": "0",
    "sOffCount": "0",
    "recoveryCount": "0",
    "score": "687",
    "rank": "1 out of 122"
}

这是我的解析器类。

public class JSONParser1 {

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

// constructor
public JSONParser1() {

}

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;

}}

这里我只想抓住其中一个值。

public class GetScore extends Activity {


private static String url = "http://example.com"


private static String TAG_NAME = "forumName";

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     setContentView(R.layout.getscore);

    JSONParser1 jParser1 = new JSONParser1();
    JSONObject json = jParser1.getJSONFromUrl(url);

    try {
        json = new JSONObject(TAG_NAME);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

  //get nickname
   try {
    json.getString("forumName");
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
  ///.... get other value for object
}   
}

我如何将其与资源ID联系起来? 任何帮助将不胜感激。

public class GetScore extends Activity {

private static String url = "http://example.com"
private static String TAG_NAME = "forumName";
private JSONParser1 jParser1 ;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.getscore);

    jParser1 = new JSONParser1();
    new GetJSONTask().execute(url);


}


    class GetJSONTask extends AsyncTask<String, Void, JSONObject> {

       private Exception exception;





protected JSONObject doInBackground(String... urls) {
    try {
        JSONParser1 jParser = new JSONParser1();
        return jParser.getJSONFromUrl(urls[0]);
    } catch (Exception e) {
        return null;
    }
}




protected void onPostExecute(JSONObject json) {
    // do all the parsing here:

    //get nickname
    try {
        // You then reset the same variable here
        // the previous object is now lost, or if it throws an exception,
        // the previously set value remains (whether null or not)
        json = new JSONObject(TAG_NAME);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // This object could easily be null, or could be valid if the previous
    // call failed
    try {
        json.getString("forumName");
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }}}}

3 个答案:

答案 0 :(得分:1)

问题正在发生,因为您正在尝试在UI线程上执行网络操作。您需要使用后台线程进行网络操作。

使用AsyncTask,如下所示:

public class GetScore extends Activity {

    private static String url = "http://example.com"
    private static String TAG_NAME = "forumName";
    private JSONParser1 jParser1 ;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.getscore);

        jParser1 = new JSONParser1();
        new GetJSONTask().execute(url);

        // do not parse here..
        ...
        ...
    }
    ...
    ...

 class GetJSONTask extends AsyncTask<String, Void, JSONObject> {

    private Exception exception;

    protected JSONObject doInBackground(String... urls) {
        try {
            JSONParser1 jParser = new JSONParser1();
            return jParser.getJSONFromUrl(urls[0]);
        } catch (Exception e) {
            return null;
        }
    }

    protected void onPostExecute(JSONObject json) {
        // do all the parsing here:

        try {
            String forumName = json.getString("forumName");
            Log.i("POST FORUM NAME:", forumName);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } 
 }
}

参考:http://developer.android.com/reference/android/os/AsyncTask.html

onPostExecute()方法中添加了一个简单的日志选项,它按预期显示了论坛的名称。

enter image description here

答案 1 :(得分:0)

可能不是答案,但这似乎是可疑的:

JSONParser1 jParser1 = new JSONParser1();
JSONObject json = jParser1.getJSONFromUrl(url); 
// you get a JSON object from the URL
// you never actually use the value you get from the web page    

try {
    // You then reset the same variable here
    // the previous object is now lost, or if it throws an exception,
    // the previously set value remains (whether null or not)
    json = new JSONObject(TAG_NAME); 
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

// This object could easily be null, or could be valid if the previous
// call failed
try {
    json.getString("forumName");
} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

我不知道出了什么问题,但看起来你有一个NullPointerException,或者至少它是没有额外知识的罪魁祸首。您可能需要花些时间来学习处理异常的正确方法。您当前只打印堆栈跟踪的方法是正确。

您需要查看代码,并确保了解可能采用的所有路径,包括例外情况。请记住,当我们有异常浮动时,代码路径不再是线性的。

我无法找到关于处理异常问题的好文章,我个人从Joshua Bloch的Effective Java中学到了很多,并且高度建议阅读它以改进你的代码。

答案 2 :(得分:0)

所以我用这种方式将它添加到我的布局中。谢谢Amulya的帮助

class GetJSONTask extends AsyncTask<String, Void, JSONObject> {



    protected JSONObject doInBackground(String... urls) {
        setContentView(R.layout.getscore2);


        try {
        JSONParser1 jParser = new JSONParser1();
        return jParser.getJSONFromUrl(urls[0]);
    } catch (Exception e) {
        return null;
    }
}

protected void onPostExecute(JSONObject json) {
    // do all the parsing here:

    try {
        String forumName = json.getString("forumName");
        final TextView id1 = (TextView)findViewById(R.id.forumUser);
        id1.setText(forumName);


        Log.i("POST FORUM NAME:", forumName);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }