【问题标题】:Parsing JSON api starting from an array - [从数组开始解析 JSON api - [
【发布时间】:2013-12-02 13:58:35
【问题描述】:

我无法解析我的 JSON API -

[
   {
      "Id":1,
      "FirstName":"admin",
      "LastName":"admin",
      "Mobile":null,
      "Email":"rajaish.rolen@gmail.com",
      "UserName":"admin",
      "password":"admin",
      "RoleID":0,
      "CreationDate":"2013-11-15T00:00:00",
      "ModificationDate":"2013-11-15T00:00:00"
   }
]

我已经在线阅读了一些教程,其中包含一个 JSONParser 类,其中有一个返回 JSONObject 的 getJSONFromURL 方法。但在所有这些教程中,他们的 API 都从 JSON Object { 开始,而我的 API 从数组 [.我需要进行哪些更改才能解析此 api?还有其他方法吗?请帮帮我,这已经困扰了我 3 天了。

这是我的 JSONParser 类 -

package com.example.projectfortab;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {
    static InputStream is = null;
    static JSONArray jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {
    }

    public JSONArray getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            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 JSONArray(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;
    }
}

这就是我正在做的解析它 -

private static final String url = (Some url);                               
private static final String TAG_ID = "CreationDate";
private static final String TAG_FIRSTNAME = "password";
private static final String TAG_LASTNAME = "LastName";
String id;
JSONArray user = null; here


private class JSONParse extends AsyncTask<String, String, JSONArray> {
    private ProgressDialog pDialog;

    @Override
    protected JSONArray doInBackground(String... params) {
    JSONParser jParser = new JSONParser();
     JSONArray json = jParser.getJSONFromUrl(url);
        System.out.println("LENGTH" + json.length());
    try {
        JSONObject json1 = json.getJSONObject(0);
        if(json1.has(TAG_ID))
            id = json1.getString(TAG_ID);
        else
            System.out.println("NO SUCH KEY");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    Log.d("anush", "ID From JSON : " + id);
    return json;
}

当我尝试这个时,logcat 显示 -

11-19 12:39:44.812: E/JSON Parser(29746): Error parsing data org.json.JSONException: Value {"ExceptionType":"System.NullReferenceException","Message":"An error has occurred.","StackTrace":"   at Lifestyle.Models.UserLoginRepository.Save(UserLogin item) in D:\\project\\LifestyleSolution2\\LifestyleSolution\\LifestyleSolution\\Lifestyle\\Models\\Repository\\UserLoginRepository.cs:line 83\r\n   at Lifestyle.Controllers.UserController.Post(UserLogin user) in D:\\project\\LifestyleSolution2\\LifestyleSolution\\LifestyleSolution\\Lifestyle\\Controllers\\UserController.cs:line 51","ExceptionMessage":"Object reference not set to an instance of an object."} of type org.json.JSONObject cannot be converted to JSONArray

11-19 12:39:44.842: E/AndroidRuntime(29746): FATAL EXCEPTION: AsyncTask #1
11-19 12:39:44.842: E/AndroidRuntime(29746): java.lang.RuntimeException: An error occured while executing doInBackground()
11-19 12:39:44.842: E/AndroidRuntime(29746):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-19 12:39:44.842: E/AndroidRuntime(29746):    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-19 12:39:44.842: E/AndroidRuntime(29746):    at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-19 12:39:44.842: E/AndroidRuntime(29746):    at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-19 12:39:44.842: E/AndroidRuntime(29746):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-19 12:39:44.842: E/AndroidRuntime(29746):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-19 12:39:44.842: E/AndroidRuntime(29746):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-19 12:39:44.842: E/AndroidRuntime(29746):    at java.lang.Thread.run(Thread.java:856)
11-19 12:39:44.842: E/AndroidRuntime(29746): Caused by: java.lang.NullPointerException
11-19 12:39:44.842: E/AndroidRuntime(29746):    at com.example.projectfortab.FirstActivity$JSONParse.doInBackground(FirstActivity.java:260)
11-19 12:39:44.842: E/AndroidRuntime(29746):    at com.example.projectfortab.FirstActivity$JSONParse.doInBackground(FirstActivity.java:1)
11-19 12:39:44.842: E/AndroidRuntime(29746):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-19 12:39:44.842: E/AndroidRuntime(29746):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-19 12:39:44.842: E/AndroidRuntime(29746):    ... 4 more

【问题讨论】:

  • {} 是对象表示法,[] 是数组表示法
  • 希望您在 3 天内学会如何在String 中获得回复。现在你必须创建JSONArray jArray = new JSONArray(response);
  • 如果要将您的 API 从数组更改为对象,您必须更改对 json 结果进行编码的方式,但是由于您确实显示了代码的任何 api 方面,因此不确定要建议多少.
  • @Neeraj Mathur 看看我的答案。

标签: java android json eclipse parsing


【解决方案1】:

试试这个:

        URL url1 = new URL("YOUR_URL");
        HttpURLConnection request1 = (HttpURLConnection) url1.openConnection();
        request1.setRequestMethod("GET");
        request1.connect();
        String responseBody = convertStreamToString(request1.getInputStream());
        JSONArray jsonArray = new JSONArray(responseBody);
        for (int i = 0; i < jsonArray.length(); i++) {
            String email = jsonArray.getJSONObject(i).getString("Email");
            System.out.println(email);

            //... Similarly you can parse all the objects..
        }

上述类中使用的方法:

private static String convertStreamToString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }
        } catch (IOException e) {
        } finally {
            try {
                is.close();
            } catch (IOException e) {
            }
        }

        return sb.toString();
    }

【讨论】:

  • 它完成了这项工作,数据正在解析,但是在源代码中将整个api编写为字符串效率不高我猜,假设如果还有100个对象,那么呢?我会在代码中将 100 个对象作为字符串编写吗?一定有更好的方法。
  • @NeerajMathur ,你不必写成字符串,你必须在这里传递你从 url 得到的响应
  • 好的,但还有一件事,看看我的 JSONParser 类,有一个名为“json”的字符串,这应该是来自 api 的响应,但这是 null。那么,我的 JSONParser 类有什么问题吗?
  • @NeerajMathur 网址是什么??
【解决方案2】:
 try {
        JSONArray jarray = new JSONArray(Resoponsedata);
       JSONObject jobject = jarray.getJSONObject(0);
        String id =  jobject .getString("Id");
                ---------------
    } catch (JSONException e) {
        e.printStackTrace();
    }

参考http://jsontree.com/

【讨论】:

    【解决方案3】:

    试试这个..

      String request = value[0];
      response = webAPIRequest.performPost_String(request,null);
      if(response != null)
        {
                    Log.i("Message Send Respopnce:==",response);
                    try {
                        JSONObject j_object_main=new JSONObject(response);
                        JSONObject j_object_data=j_object_main.optJSONObject("data");
    
                        success=j_object_data.optString("Success");
    
                        if(success.equalsIgnoreCase("1"))
                        {
    
                            JSONArray jarray_news=j_object_data.optJSONArray("newInfo");
    
                for(int i=0;i<jarray_news.length();i++)
                {
         }
    

    【讨论】:

      【解决方案4】:

      尝试如下:

      JSONArray m_arry = new JSONArray("your response");
          for (int i = 0; i < m_arry.length(); i++) 
            {
          JSONObject m_mydetail = m_arry.getJSONObject(i);
      
                  String id=m_mydetail.getString("Id");
                  String firstName=m_mydetail.getString("FirstName");
                  String lastName=  m_mydetail.getString("LastName"); 
                  String email =m_mydetail.getString("Email");
                 ...............................
                  //and so on.
           }
      

      更多请查看HERE

      【讨论】:

      • 我尝试了相同但 logcat 显示 - 11-19 12:07:36.263: E/JSON Parser(22473): Error parsing data org.json.JSONException: Valueof type org.json.JSONObject cannot转换为 JSONArray
      • @NeerajMathur 也可以在您的问题中发布您的 logcat 错误吗?
      【解决方案5】:

      读取对字符串的响应,然后使用以下代码。

          try {
              JSONObject jsonObject = new JSONArray("ResponseString").getJSONObject(0);
              jsonObject.getString("RequiredStrings");
                          ----
                          ---- 
          } catch (JSONException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多