简体   繁体   English

JSONObject转换为String,API 10和API19中的结果不同

[英]JSONObject to String, different result in API 10 and API19

I have the following code for convert a JSONObject into a StringEntity that I will send via a HTTP post request. 我有以下代码将JSONObject转换为StringEntity,该对象将通过HTTP发布请求发送。 This is working fine on an actual device with KITKAT, but when I try in the emulator with API10, I got an error from the server. 在带有KITKAT的实际设备上,这可以正常工作,但是当我尝试使用API​​10在仿真器中时,服务器出现错误。

JSONObject jsonRequest = new JSONObject();
//filling the jsonRequest with data
System.out.println(jsonRequest.toString());
StringEntity se = new StringEntity(jsonRequest.toString());

I have realize that the way JSONObject#toString works is different in API10 and API19 and that is why the server is returning a 500 error. 我已经意识到JSONObject#toString的工作方式在API10和API19中是不同的,这就是为什么服务器返回500错误的原因。 This is what the println outputs: 这是println输出的内容:

API19 API19

{"expenses":[{"category":"660","attachment":{"data":"\/9j\/4...

API10 API10

{"expenses":[{"category":"660","attachment":"{data=\/9j\/4...

Note the equals symbol(=) instead of colon (:) and the different position of the quotes ("). 请注意,用等号(=)代替冒号(:)以及引号的不同位置(“)。

The json should look like json应该看起来像

{
   "expenses":[
      {
         "category":"123",
         "attachment":{
            "data":"akcsdc...sdc"
         }
      }
   ]
}

Why is this happening? 为什么会这样呢? Is there a better way to do this? 有一个更好的方法吗?

Thanks. 谢谢。

Finally I found where the problem was, I was mapping the attachment object as a HashMap, I changed it to a JSONObject and now it works. 最终,我发现了问题所在,将附件对象映射为HashMap,将其更改为JSONObject,现在它可以工作了。

JSONObject jsonObj = new JSONObject();
Map<String, Object> attachmentMap = new HashMap<String, Object>();
attahmentMap.put("data", dataString);
jsonObj.put("attachment", attachmentMap);

Changed to 变成

JSONObject jsonObj = new JSONObject();
JSONObject attachmentJson = new JSONObject();
attachmentJson.put("data", dataString);
jsonObj.put("attachment", attachmentJson);

Yes its going wrong when you convert it from HashMap. 是的,当您从HashMap进行转换时,它出了问题。 I used org.json.simple.JSONObject 我用org.json.simple.JSONObject

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM