在android中添加到json对象的链接

时间:2013-02-27 07:15:55

标签: android json creation

 JSONArray albumarray=new JSONArray();
   JSONObject imgobj=new JSONObject();
    imgobj.put("thumb", filepath.get(i));
    imgobj.put("main", filepath.get(i));
    albumarray.put(imgobj);
    JSONObject albumjson=new JSONObject();
   albumjson.put(albumname,albumarray);

当我使用

将albumjson转换为字符串时
albumjson.toString()

我的输出如下。

{\"test2\":\"[{\\\"thumb\\\":\\\"http:\\\\\\/\\\\\\/dev.mysite.in\\\\\\/mysite\\\\\\/sites\\\\\\/default\\\\\\/files\\\\\\/512da541b31fe.jpg\\\",\\\"main\\\":\\\"http:\\\\\\/\\\\\\/dev.mysite.in\\\\\\/mysite\\\\\\/sites\\\\\\/default\\\\\\/files\\\\\\/512da541b31fe.jpg\\\"}]\"}

我需要的正确格式是

{"test2":[{"thumb":"http://dev.mysite.in/mysite/sites/default/files/512d9bdced1f2.jpg","main":"http://dev.mysite.in/mysite/sites/default/files/512d9bdced1f2.jpg"},{"thumb":"http://dev.mysite.in/mysite/sites/default/files/512d9be134cb8.jpg","main":"http://dev.mysite.in/mysite/sites/default/files/512d9be134cb8.jpg"}]}

如何替换额外的斜杠。

2 个答案:

答案 0 :(得分:2)

使用JSONObject.getString('keyName')方法代替toString()

修改

你应该首先理解为什么那些额外的\\出现了。它是"的转义字符。因此,它非常需要并且是部分的JSON编码< / em> .Hence,应该总是使用上面的方法来获取密钥的值。

除此之外,您可以尝试:

JSONObject.toString(4)其中4实际上是缩进空格并查看它是否有帮助。否则,除了替换那些额外的\\之外别无其他选择

myJsonString.replaceAll("\\","");

 myJsonString=myJsonString.replaceAll("\\\\",""); 

第二次编辑:

您发送的字符串非常适合发送到任何服务器。您需要decode服务器端的字符串{J},然后使用它。

如果您使用的是.NET,则可以看到this。或者,如果您在其他平台上,则需要了解如何在该平台上解码为JSON。

答案 1 :(得分:-1)

这里有两件事:

  1. 您的工具让您感到困惑。当它显示输出时:

    "{\"test2\":\"[{\\\"thumb\\\":\\\"http:\\\\\\/\\\\\\/dev.lrcdn.in\\\\\\/shiaspark\\\\\\/sites\\\\\\/default\\\\\\/files\\\\\\/512da541b31fe.jpg\\\",\\\"main\\\":\\\"http:\\\\\\/\\\\\\/dev.lrcdn.in\\\\\\/shiaspark\\\\\\/sites\\\\\\/default\\\\\\/files\\\\\\/512da541b31fe.jpg\\\"}]\"}"
    

    它告诉您结果是一个包含以下内容的字符串:

    {"test2":"[{\"thumb\":\"http:\\\/\\\/dev.lrcdn.in\\\/shiaspark\\\/sites\\\/default\\\/files\\\/512da541b31fe.jpg\",\"main\":\"http:\\\/\\\/dev.lrcdn.in\\\/shiaspark\\\/sites\\\/default\\\/files\\\/512da541b31fe.jpg\"}]"}
    
  2. 取出该字符串并对其进行格式化:

    {"test2":
     "[{\"thumb\":\"http:\\\/\\\/dev.lrcdn.in\\\/shiaspark\\\/sites\\\/default\\\/files\\\/512da541b31fe.jpg\",\"main\":\"http:\\\/\\\/dev.lrcdn.in\\\/shiaspark\\\/sites\\\/default\\\/files\\\/512da541b31fe.jpg\"}]"
    }
    

    我们可以看到你构造了一个包含json编码字符串的json对象,而不是嵌套的jsonobject。无论出于何种原因,您的代码都具有以下效果:

    JSONArray albumarray=new JSONArray();
    JSONObject imgobj=new JSONObject();
    imgobj.put("thumb", filepath.get(i));
    imgobj.put("main", filepath.get(i));
    albumarray.put(imgobj);
    
    JSONObject albumjson = new JSONObject();
    albumjson.put(albumname, albumarray.toString());
    

    这听起来像是你的json库中的一个错误