如何从JSON获取String值?

时间:2015-07-27 05:54:40

标签: android json

我是android开发的初学者,并尝试使用listView制作和应用程序,显示JSON的字符串值。

以下是我的代码的一部分:

String jsonResult = "";
int animal_id = 0;
String ani_name = "asd", sci_name = "fgh";

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bestiary);

.
.
.

    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {

            for (int i = 0; i < 10; i++) {
                if (position == i) {
                    Thread t = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Looper.prepare();
                            uploadToServer();
                            Log.d(TAG, "my thread works");
                            Log.d(TAG, jsonResult);

                            testReceiveData(jsonResult, position); //It said position needs to be declared final above
                            Log.d(TAG, "maybe this one works too");
                            Log.d(TAG, ani_name);
                        }
                    });
                    Log.d(TAG, "thread get started");
                }
                Intent intent = new Intent(BestiaryActivity.this, BestiaryDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("aniString", ani_name);
                bundle.putString("sciString", sci_name);

                intent.putExtras(bundle);
                startActivity(intent);
            }
        }
    });
}

public void testReceiveData(String jsonResult, int position) {
    try {
        JSONArray arr = new JSONArray(jsonResult);
        JSONObject jsonObj = arr.getJSONObject(position);
        String animalName = jsonObj.getString("name");
        String scienceName = jsonObj.getString("sci_name");
        Log.d(TAG, "It gets JSONObject");

        ani_name = animalName;
        sci_name = scienceName;
        Log.d(TAG, "Convert them");

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

@SuppressWarnings("deprecation")
public boolean uploadToServer() {
    try {
        String responseString = null;
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(urlServer);


        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

        nameValuePairs.add(new BasicNameValuePair("aniName", Integer.toString(aniNumber)));

        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httpPost);
        Log.d(TAG, "amHere");

        HttpEntity result = response.getEntity();
        if (result != null) {
            InputStream input = result.getContent();
            String resultString = convertStreamToString(input);
            Log.d(TAG, resultString);
            jsonResult = resultString;
            Log.d(TAG, "jesonResult works");
        } else {
            Log.d(TAG, "broke in repsonse");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return true;
}

然后我的JSON文件如下所示:

物种:{“animal_id”:“1”,“name”:“American Robin”,“sci_name”:“Turdus migratorius”}

我的期望是ani_name更改为American Robin并将sci_name更改为Turdus migratorius,因此我的下一个活动显示此值,但ani_name仍为asd且sci_name为fgh。

我检查了Log.d(TAG,jsonResult);有JSON

我可以问你我做错了什么以及如何解决它?

哦,这些来自logcat

07-27 01:49:12.435    6867-6867/com.example.kange1.bert I/art﹕ Late-enabling -Xcheck:jni
07-27 01:49:12.639    6867-6885/com.example.kange1.bert D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true
07-27 01:49:12.646    6867-6867/com.example.kange1.bert D/Atlas﹕ Validating map...
07-27 01:49:12.669    6867-6885/com.example.kange1.bert I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:379>: QUALCOMM Build: 01/15/15, ab0075f, Id3510ff6dc
07-27 01:49:12.670    6867-6885/com.example.kange1.bert I/OpenGLRenderer﹕ Initialized EGL, version 1.4
07-27 01:49:12.694    6867-6885/com.example.kange1.bert D/OpenGLRenderer﹕ Enabling debug mode 0
07-27 01:49:18.890    6867-6867/com.example.kange1.bert D/BestiaryActivity﹕ thread get started
07-27 01:49:18.958    6867-6867/com.example.kange1.bert D/AndroidRuntime﹕ Shutting down VM
07-27 01:49:18.959    6867-6867/com.example.kange1.bert E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.kange1.bert, PID: 6867
java.lang.ArrayIndexOutOfBoundsException: length=9; index=9
        at com.example.kange1.bert.BestiaryActivity$1.onItemClick(BestiaryActivity.java:216)
        at android.widget.AdapterView.performItemClick(AdapterView.java:305)
        at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
        at android.widget.AbsListView$PerformClick.run(AbsListView.java:3053)
        at android.widget.AbsListView$3.run(AbsListView.java:3860)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
07-27 01:49:18.981    6867-7152/com.example.kange1.bert D/BestiaryActivity﹕ amHere
07-27 01:49:18.982    6867-7152/com.example.kange1.bert D/BestiaryActivity﹕ Species : {"animal_id":"1","name":"American Robin","sci_name":"Turdus migratorius"}
07-27 01:49:18.982    6867-7152/com.example.kange1.bert D/BestiaryActivity﹕ jesonResult works
07-27 01:49:18.982    6867-7152/com.example.kange1.bert D/BestiaryActivity﹕ my thread works
07-27 01:49:18.982    6867-7152/com.example.kange1.bert D/BestiaryActivity﹕ Species : {"animal_id":"1","name":"American Robin","sci_name":"Turdus migratorius"}
07-27 01:49:18.982    6867-7152/com.example.kange1.bert W/System.err﹕ org.json.JSONException: Value Species of type java.lang.String cannot be converted to JSONArray
07-27 01:49:18.982    6867-7152/com.example.kange1.bert W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:111)
07-27 01:49:18.983    6867-7152/com.example.kange1.bert W/System.err﹕ at org.json.JSONArray.<init>(JSONArray.java:96)
07-27 01:49:18.983    6867-7152/com.example.kange1.bert W/System.err﹕ at org.json.JSONArray.<init>(JSONArray.java:108)
07-27 01:49:18.983    6867-7152/com.example.kange1.bert W/System.err﹕ at com.example.kange1.bert.BestiaryActivity.testReceiveData(BestiaryActivity.java:262)
07-27 01:49:18.983    6867-7152/com.example.kange1.bert W/System.err﹕ at com.example.kange1.bert.BestiaryActivity$1$1.run(BestiaryActivity.java:161)
07-27 01:49:18.983    6867-7152/com.example.kange1.bert W/System.err﹕ at java.lang.Thread.run(Thread.java:818)
07-27 01:49:18.983    6867-7152/com.example.kange1.bert D/BestiaryActivity﹕ maybe this one works too
07-27 01:49:18.983    6867-7152/com.example.kange1.bert D/BestiaryActivity﹕ asd

3 个答案:

答案 0 :(得分:1)

使用json对象类的getString()方法。 例: 格式:

{
  "name":"john",
  "country":"India"
}

现在,如果您想获取名称

的值
JSONObject jsonObj = new JSONObject(formatStr);
String nameStr = jsonObj.getString("name");

答案 1 :(得分:0)

请参阅以下代码中的评论:

public void testReceiveData(String jsonResult, int position) {
    try { 
        JSONArray arr = new JSONArray(jsonResult); // jsonResult is a jaon object and you are decoding it in JSONArray. See exception carefully.
     // You code is actually written to parse a JSONArray so i think you should make it array.
        JSONObject jsonObj = arr.getJSONObject(position);
        String animalName = jsonObj.getString("name");
        String scienceName = jsonObj.getString("sci_name");
        Log.d(TAG, "It gets JSONObject");

        ani_name = animalName;
        sci_name = scienceName;
        Log.d(TAG, "Convert them");

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

您的代码正在解析JSONArray,因此您应该使jsonResult成为JSONArray,如:{"animal_id":"1", "name":"American Robin", "sci_name":"Turdus migratorius"},但要跟踪位置变量,它不应该超出范围。

答案 2 :(得分:-1)

你不需要使用jsonarray。使用jsonobject并从JSON获取字符串值。

这是代码: jsonResult = {“animal_id”:“1”,“name”:“American Robin”,“sci_name”:“Turdus migratorius”}

public void testReceiveData(String jsonResult,int position){     试试{

   JSONObject jsonObj = new JSONObject(jsonResult);

    String animalName = jsonObj.getString("name");
    String scienceName = jsonObj.getString("sci_name");
    Log.d(TAG, "It gets JSONObject");

    ani_name = animalName;
    sci_name = scienceName;
    Log.d(TAG, "Convert them");

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

}