Java的字符串转换为JSON不能做 [英] Java String conversion to JSON can not be done

查看:199
本文介绍了Java的字符串转换为JSON不能做的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有JSON这是我从服务器获取:

I have JSON which I get from server:

 "[{\"id\":\"1\",\"name\":\"Milos\",\"city\":\"Smederevo\",\"email\":\"milos\",\"password\":\"\"},
 {\"id\":\"3\",\"name\":\"Boban\",\"city\":\"Beograd\",\"email\":\"bole\",\"password\":\"\"},
 {\"id\":\"4\",\"name\":\"Pele\",\"city\":\"Brazil\",\"email\":\"pele@pele.com\",\"password\":\"\"},
 {\"id\":\"5\",\"name\":\"admin\",\"city\":\"Smederevo\",\"email\":\"admin\",\"password\":\"\"}]"

我使用的JSON和发送给我的线程(线程的android):

I am using that json and sending to my thread (android thread):

  try {
            // Method from which I am getting Json described above
            String s = dm.getAllUsers();

            /*JSONParser jp = new JSONParser();             
            JsonElement jelement = new JsonParser().parse(s);   
                JsonArray array1 = jelement.getAsJsonArray();*/

            JSONArray array = new JSONArray(s);
            for (int i = 0; i < array.length(); i++) {

                 JSONObject menuObject = array.getJSONObject(i);

                 // doing something with the object
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

我不能处理的Json的。
我收到错误java.lang.String中不能转化为JSONArray。
一个知道问题是由\\造成的,我只是不知道如何摆脱\\。

I can not process that Json at all. I am getting the error "java.lang.String cannot be converted to JSONArray". A know that problem is caused by "\", and I just do not know how to get rid of "\".

我试过:

1) s.replace("\\", "");
2) s.replace("\"", "'");
3) s.replaceAll("\\", "");
4) s.replaceAll("\"", "'");

为了抹去\\,但更换根本不反应。
我也试图与谷歌GSON-2.2.2库(注释下的code以上,下方法)来解决问题。

In order to erase "\" but replace do not react at all. I also tried to solve problem with "google-gson-2.2.2" library (code under the comment above, under the method).

任何意见,请?

推荐答案

问题已经解决了:

 1) s = s.trim();
 2) s = s.substring(1, s.length()-1);
 3) s = s.replace("\\", "");

我的JSON已经检索与年初和年底的双引号。我不知道字符串变量怎么也无法弄清楚,双引号是开端,并为字符串收官。

My json has been retrieved with "double quotes" on the beginning and on the end. I do not know how string variable can not figure out that "double quotes" is for "beginning" and for "ending" of string.

感谢您大家的帮助。

这篇关于Java的字符串转换为JSON不能做的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆