如何在java中将json数据转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22914808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 18:56:08  来源:igfitidea点击:

How to convert a json data to string in java

javajsonarraysjsonobject

提问by ss3419670

I want to convert json data to string

我想将json数据转换为字符串

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:

它向我展示了 json 数据,但给了我这个错误:

{"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

如果您有任何解决方案,请帮助我。提前致谢

采纳答案by codefreaK

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.

在您的代码中,您从 URL 读取 json 数据。我只是复制了您的数据并将其粘贴到一个文件中,然后在您的 url 关闭时读取了该文件。在这里,我一步一步地展示了如何解析您的 json 对象和其中的内容。为此,我使用了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

你的 Json 对象

{"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

您包含在 json 对象中的 Json 数组

[{"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

你在数组中的 Json 对象

{"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

你的 Json 对象 id_lang 属性值 = 4

4

enter image description here

在此处输入图片说明

回答by Mena

Your JSON is not an array.

您的 JSON 不是数组。

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

它是一个具有一个属性的 JSON 对象:modeles,其值为数组。

Parse the root as JsonObject.

将根解析为JsonObject.

回答by Nambi

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

{->代表JSONObject和 [->代表JSONArray,先获取jsonObject再获取其中的数组。

I tried with jsonObjectpackage import the jar

我尝试使用jsonObjectpackage 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("*********");
      }