1

I want to convert json data to string

import java.io.BufferedReader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONArray;
import org.json.JSONObject;
public static void main(String[] args) throws Exception
{

    URL url = new URL("http://192.168.1.13/test/ProductWb.php?productId=9");
    HttpURLConnection conn ;
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setReadTimeout(60);
    conn.setRequestProperty("Accept", "application/json");
    String json="";

    json = readUrl(conn);
           System.out.println(json);
           JSONObject jsonObject=new JSONObject(json);
           JSONArray jarray=jsonObject.getJSONArray("modeles");
           JSONObject  modele= jarray.getJSONObject("modele");
           for (int i=0;i<modele.length();i++) {
               System.out.println(modele(i).getString("id_product"));
                System.out.println(modele(i).getString("meta_title"));
                System.out.println("*********");
              }


}

its show me the json data but give me this the error:

{"modeles":[{"modele":{"id_product":"9","id_shop":"1","id_lang":"4","description":null,"description_short":"<pre>Peugeot 208<\/pre>","info_prix":"","info_1":null,"info_2":null,"info_3":null,"info_4":null,"info_5":null,"link_rewrite":"208","meta_description":"Peugeot 208","meta_keywords":"peugeot 208","meta_title":"Peugeot 208","name":"208","available_now":"","available_later":""}}]}
Exception in thread "main" java.lang.IllegalStateException: This is not a JSON Array.
at com.google.gson.JsonElement.getAsJsonArray(JsonElement.java:106)
at com.autoreduc.services.TestProduct.main(TestProduct.java:59)

help me if you have any solution. thanks in advance

4
  • 3
    It's pretty clear that This is not a JSON Array. Also, where do you see a NullPointereException? Commented Apr 7, 2014 at 14:07
  • 1
    You should most definitely familiarize yourself with the json format. Commented Apr 7, 2014 at 14:08
  • How do you typically read your exception stack traces? Commented Apr 7, 2014 at 14:10
  • He means that you state in your question that you've got a NullPointereException (sic), when there's no mention of that exception in your stack trace. It's an IllegalStateException Commented Apr 7, 2014 at 14:12

4 Answers 4

6

Your JSON is not an array.

It's a JSON object with one property: modeles, whose value is the array.

Parse the root as JsonObject.

Sign up to request clarification or add additional context in comments.

1 Comment

You got to love a library construct for interpreting a format that requires you to understand the format and know what you've got before you interpret it!
5

You can use ObjectMapper to convert objects to json string:

ObjectMapper mapper = new ObjectMapper();
try {
  String json = mapper.writeValueAsString(cat);
  System.out.println("ResultingJSONstring = " + json);
  //System.out.println(json);
} catch (JsonProcessingException e) {
   e.printStackTrace();
}

1 Comment

You need to add this as well mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
1

{->represents JSONObject and [->represents the JSONArray, first get the jsonObject and then get the array in it.

I tried with jsonObject package import the jar

 JSONObject jsonObject=new JSONObject(yourstring);
    JSONArray jarray=jsonObject.getJSONArray("modeles");
 JSONObject  modele= jarray.getJSONObject("modele");
   for (int i=0;i<modele.length();i++) {
       System.out.println(modele(i).getString("id_product"));
        System.out.println(modele(i).getString("meta_title"));
        System.out.println("*********");
      }

8 Comments

what is JSONObject because its not accepted by the eclipse?
@ss3419670 Please include the relevant imports in your question.
i do it but it give me to add cast to jarray.get(i) ?
yeah i look it , i found this error with your last answer
@ss3419670 sorry,i didn't recognize your json please see my final edit
|
0

In your code you read the json data from a URL. I just copied your data and pasted it in a file and read the file as your url was down. Here step by step I have shown how to parse your json object and content inside it. For this I used java-json-schema.jar.

    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Iterator;
    import org.json.simple.JSONArray;
    import org.json.simple.JSONObject;
    import org.json.simple.parser.JSONParser;
    import org.json.simple.parser.ParseException;
    public class Tets {

        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            JSONParser parser = new JSONParser();
           try{
          /*  URL url = new URL("http://192.168.1.13/test/ProductWb.php?productId=9");
            HttpURLConnection conn ;
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setReadTimeout(60);
            conn.setRequestProperty("Accept", "application/json");*/
            String json="";

            Object obj = parser.parse(new FileReader("C:\\XXX\\XX\\src\\javapackage\\t.json"));

            JSONObject jsonObject = (JSONObject) obj;
            System.out.println(jsonObject.toJSONString());  //modeles object
            JSONArray name = (JSONArray) jsonObject.get("modeles");
            System.out.println(name.toJSONString());//array inside modeles array


            for (Object o : name)
              {
                JSONObject person = (JSONObject) o;
                 JSONObject person1 = (JSONObject)person.get("modele");
                              System.out.println(person.get("modele"));//modele object
                              System.out.println(person1.get("id_lang"));//modele attribute
              } 



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

        }
    }

OutPut

Your Json Object

{"modeles":[{"modele":{"id_lang":"4","info_5":null,"info_4":null,"link_rewrite":"208","meta_keywords":"peugeot 208","info_3":null,"info_2":null,"info_1":null,"available_now":"","meta_description":"Peugeot 208","id_product":"9","description_short":"<pre>Peugeot 208<\/pre>","description":null,"name":"208","info_prix":"","meta_title":"Peugeot 208","available_later":"","id_shop":"1"}}]}

Your Json Array contained in json Object

[{"modele":{"id_lang":"4","info_5":null,"info_4":null,"link_rewrite":"208","meta_keywords":"peugeot 208","info_3":null,"info_2":null,"info_1":null,"available_now":"","meta_description":"Peugeot 208","id_product":"9","description_short":"<pre>Peugeot 208<\/pre>","description":null,"name":"208","info_prix":"","meta_title":"Peugeot 208","available_later":"","id_shop":"1"}}]

Your Json Object inside array

{"id_lang":"4","info_5":null,"info_4":null,"link_rewrite":"208","meta_keywords":"peugeot 208","info_3":null,"info_2":null,"info_1":null,"available_now":"","meta_description":"Peugeot 208","id_product":"9","description_short":"<pre>Peugeot 208<\/pre>","description":null,"name":"208","info_prix":"","meta_title":"Peugeot 208","available_later":"","id_shop":"1"}

Your Json Object id_lang atrribute value = 4

4

enter image description here

2 Comments

i do your proposition but it give me this exception -->Can only iterate over an array or an instance of java.lang.Iterable ,in this --> code part: (Object o : name)
did you copy my whole code and and pasted it or did you write it from scratch based on my proposition

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.