如何将String转换为JsonObject?

时间:2013-06-26 06:12:32

标签: android json string

{
   "error":null,
   "countries":[
      {
         "id":1,
         "description":"Slovensko",
         "locale":"sk_SK",
         "zipRegexp":"/^\\d{3}\\ ?\\d{2}$/"
      },
      {
         "id":2,
         "description":"Česká republika",
         "locale":"cs_CZ",
         "zipRegexp":null
      },
      {
         "id":3,
         "description":"Afganistan",
         "locale":"en_EN",
         "zipRegexp":null
      }
    ]
}

依此类推,现在我需要将其转换为Android上的JsonObject。 但由于双逗号 ,我无法将其转换为String。怎么做到呢?我需要这样的想法:

JsonObjet.JsonFromString('{"error":null,"countries":[{"id":1,"description":"Slovensko","locale":"sk_SK","zipRegexp":"/^\\d{3}\\ ?\\d{2}$/"},{"id":2,"description":"Česká republika","locale":"cs_CZ","zipRegexp":null}}');

这不是答案:

JSONObject getJSON = new JSONObject("{"error":null,"countries":[{"id":1,"description":"Slovensko","locale‌​":"sk_SK","zipRegexp":"/^\\d{3}\\ ?\\d{2}$/"},{"id":2,"description":"Česká republika","locale":"cs_CZ","zipRegexp":null}}");

因为有双重逗号。

感谢

4 个答案:

答案 0 :(得分:2)

JSONObject getJSON = new JSONObject("Your String");

编辑:

String yourString = "{"+"\"error\""+":"+"\"no error\""+"}";
System.out.println(yourString );

然后yourString将是{"error":"no error"}。对您拥有的String实现相同的方式。然后将上面的yourString转换为JSONObject为

JSONObject getJSON = new JSONObject(yourString);

答案 1 :(得分:2)

你如何得到JSon ???如果从HttpClient获取它,则将其作为InputStream获取,并使用bufferedReader将其转换为String缓冲区。

答案 2 :(得分:1)

JSONObject jsonObject = new JSONObject(res);

答案 3 :(得分:1)

试试这个:

        InputStream mIs = null;
        String result = "";
        JSONObject jObjectLogin = null;

           HttpClient httpclient = new DefaultHttpClient();
           String urlWithNoSpace=  url.replace(" ", "%20");
           HttpGet httpget = new   HttpGet(urlWithNoSpace);
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            mIs = entity.getContent();

            String result = "";
            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(mIs,"UTF-8"),8);
            StringBuilder stringBuilder = new StringBuilder();
            String line = null;

            while ((line = bufferReader.readLine()) != null) {

             //if require change or edit this condition.     
             if(line.trim().equals("\n"))
                    continue;
                stringBuilder.append(line + "\n");
            }
            mIs.close();
            result=stringBuilder.toString();

现在,根据字符串格式(采用Json格式),您可以从中获取数组和对象。

     JSONObject jsonObject=result ;
     JSONArray jsonArray=jsonObject.getJSONArray("countries");

现在放置循环并从数组中找到值。