简体   繁体   English

Android将String转换为JSONObject

[英]Android Convert String to JSONObject

I want to convert a string to JSONObject. 我想将字符串转换为JSONObject。 Below is sample code. 以下是示例代码。

String str = "{"time": 1449838598.0999202, "Label": "Shirt", "Price": 52}";
JSONObject obj = new JSONObject(str);

But after conversion time becomes 1.4498385980999203E9. 但转换时间后变为1.4498385980999203E9。 Any Help will be appreciated. 任何帮助将不胜感激。 Thanks 谢谢

If you really want it to be formatted like that then make it into a string instead of a number. 如果你真的希望它被格式化,那么把它变成一个字符串而不是一个数字。 Just add double quotes around the item. 只需在项目周围添加双引号即可。 But if your using it for a calculation on the other end, i would leave it as is as you'll have to convert it back to a int anyway. 但是如果你在另一端使用它进行计算,我会保留它,因为你必须将它转换回int。 If you want to use gson as an alternative check here: How to prevent Gson from converting a long number (a json string ) to scientific notation format? 如果你想在这里使用gson作为替代检查: 如何防止Gson将长数字(json字符串)转换为科学记数法格式?

Write it like this in double quote. 用双引号将它写成这样。 "1449838598.0999202" “1449838598.0999202”

Like Abhishek said, write time & price in double quote as "1449838598.0999202" and "52". 像Abhishek所说,用双引号写出时间和价格为“1449838598.0999202”和“52”。 Then you can save the string to Gson, and then convert it to Json. 然后你可以将字符串保存到Gson,然后将其转换为Json。

String str = "{"time": "1449838598.0999202", "Label": "Shirt", "Price": "52"}";
Gson gson = new Gson();
String json = gson.toJson(str);

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

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