E
E
Egor Vavilov2014-07-05 10:26:06
Java
Egor Vavilov, 2014-07-05 10:26:06

Java: Why can't parse JSON?

Good afternoon! I am getting a JSON file from the server like this:

HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(params[0]); // params[0] - URL-адрес

ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

try {
    httpPost.setEntity(new UrlEncodedFormEntity(param));
    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();

    is = httpEntity.getContent();
} catch (Exception e) {
    System.out.println("Error: " + e.getMessage());
    return false;
}

Next, I process it:
try {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
    StringBuilder stringBuilder = new StringBuilder();
    String line = "";
    while ((line = bufferedReader.readLine()) != null) {
        stringBuilder.append(line + "\n");
    }
    is.close();

    // Переменная result содержит JSON-код, полученный с сервера
    result = stringBuilder.toString();

    jsonParser(result);

    return true;
} catch (Exception e) {
    System.out.println("Error: " + e.getMessage());
    return false;
}

public void jsonParser(String result) {
    text.setText(result);
    try {
        JSONObject jsonObject = new JSONObject(result);
        JSONArray entries = jsonObject.getJSONArray("plans");

        for (int i = 0; i < entries.length(); i++ ) {
            JSONObject post = entries.getJSONObject(i);
            idResult[i] = post.getString("ID");
        }
    } catch (Exception e) {
        System.out.println("Error jsonParser(): " + e.getMessage());
    }
}

As a result, an exception is triggered
Error jsonParser(): null
. Why null? How to properly process JSON that is in a string?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
E
Eserchik, 2014-07-07
@Shecspi

To begin with, you need to know exactly what the server returns to you, for this you can, for example, install the Chrome extension - Postman REST CLIENT (form your request in it and see what json structure it returns).
In your code, you do not send any data to the server, you have the following construction:

ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
-empty. You are sending a current empty header. It should be like this for example:
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
          nameValuePairs.add(new BasicNameValuePair("grant_type", "password"));
          nameValuePairs.add(new BasicNameValuePair("password", pass));
          nameValuePairs.add(new BasicNameValuePair("username", login));
          httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

Json response can be as simple as:
{
    "name": "Иванов Сергей",
    "phone": "89651102121"
}

Then here:
if(result != null){
        
    			try{
    				final JSONArray jArray = new JSONArray(result);
    	               
    				   for(int i=0;i<jArray.length();i++) 
    				      {
    					     JSONObject json_data = jArray.getJSONObject(i);
    					
    					  String  name = json_data.getString("name");
    					  String phone =json_data.getString("phone");
    				
    	                  }
    	          }catch(JSONException e1){
    				         Log.d(LOG_TAG,"Ошибка Json Parse: "+e1.toString());
    			    }
    			
    		}

Or maybe Json is complicated
{
   "Status":{
      "Name":"Подтверждена",
      "Id":2
   },
   "Description":"Описание",
   "WorkCategory":{
      "Name":"Электрика",
      "Id":1
   },
   "OrderedAt":"2014-07-04T11:00:00.000Z",
   "ClientName":"ФИО",
   "ClientAddress":"Адрес",
   "ClientPhone":"89651101010",
   "ServiceComment":"Ваш комментарий",
   "City":{
      "Name":"Москва",
      "Id":1
   },
   "Title":"Название заявки"
}

Then you need to do this:
if(result != null){
    

    try{
      
    	        JSONObject jObject = new JSONObject(result);
                        JSONArray myValue = jObject.getJSONArray("value");
    				

    				
    				
    		for (int i = 0; i < myValue.length(); i++) {
                        JSONObject c = myValue.getJSONObject(i);
                         
                        //Категория работ
                        JSONObject WorkCategoryObj = c.getJSONObject("WorkCategory");
                        String WorkCategory =WorkCategoryObj.getString("Name");
                        
                        //Город
                        JSONObject CityObj = c.getJSONObject("City");
                        String City =CityObj.getString("Name");
                        
                        //Статус
                        JSONObject StatusObj = c.getJSONObject("Status");
                        String Status =StatusObj.getString("Name");
                        
                        //Содержимое заявки
                        String Id = c.getString("Id");
                        String Num = c.getString("Num");
                        String Title = c.getString("Title");
                        String Description = c.getString("Description");
                        String CreatedAt = c.getString("CreatedAt");
                        String ArrivedAt = c.getString("ArrivedAt");
                        String OrderedAt = c.getString("OrderedAt");
                        String CompletedAt = c.getString("CompletedAt");
                        String ServiceComment = c.getString("ServiceComment");
                        String WorkerComment = c.getString("WorkerComment");
                        String ClientName = c.getString("ClientName");
                        String ClientAddress = c.getString("ClientAddress");
                        String ClientPhone = c.getString("ClientPhone");
                        String ClientComment = c.getString("ClientComment");
                        

    				}
    				
    				
    		
 			    }
    			catch(JSONException e1){
                 Log.d(LOG_TAG,"Ошибка Json Parse: "+e1.toString());
          }

M
Max, 2014-07-07
@mbelskiy

There is a chic Gson library, I advise you to familiarize yourself

V
vlad20012, 2014-07-05
@vlad20012

e.getMessage() does not give any information about the exception that occurred, you need to write e.printStackTrace() in the line below; Complete the question with what was written to the console after that, otherwise few people here have the skill of telepathic error detection.

C
Calc, 2014-07-10
@Calc

As already advised use Gson and forget
https://code.google.com/p/google-gson/

Gson gson = new Gson();

Response response = gson.fromJson(json, Response.class);

Response is your class with the fields you need and match the json string

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question