简体   繁体   English

Java中的JSON字符串到JSON

[英]JSON String to JSON in Java

I have a couple of txt files that gets some information from android's (call,messages,etc) database and stores it as a Cursor object. 我有几个txt文件从android的(调用,消息等)数据库获取一些信息并将其存储为Cursor对象。

I then convert the Cursor onto a JSON object which is then stored on a txt file on an SD card on the device. 然后我将Cursor转换为JSON对象,然后将其存储在设备上SD卡上的txt文件中。 When I read from the file I get lines as a String like this one: 当我从文件中读取时,我得到像这样的字符串:

{"date":1332969098495,"duration":0,"number":"7038673588","Device_ID":"streak"}

I have to store the values of the String onto a MySQL table. 我必须将String的值存储到MySQL表中。 Is there a way that I can convert this back onto a JSON or maybe a Map? 有没有办法可以将它转换回JSON或Map?

I thought about editing the String so the values are surrounded by a single quote and use the MySQL syntax to simply load the fields on the file. 我想过编辑String所以这些值被单引号包围,并使用MySQL语法简单地加载文件中的字段。

Thanks! 谢谢!

You need to use JSon-lib (or) GSon libraries for this purpose. 为此,您需要使用JSon-lib (或) GSon库。

Example GSon code would be: 示例GSon代码将是:

YourObject obj = gson.fromJson(inputJson, YourObject.class);

Note: YourObject is java class with getter/setter. 注意: YourObject是带有getter / setter的java类。

You can create a JSONObject from the string that you have. 您可以从您拥有的字符串创建JSONObject。 That will pretty much give the same functionality as that of java.util.Map. 这几乎可以提供与java.util.Map相同的功能。 For eg, 例如,

String jsonStr = "json representation of your data";
JSONObject jObj = new JSONObject(jsonStr);
jObj.get(yourKeyString);
//do more with your jObj here...

Hope this helps. 希望这可以帮助。 Refer the JSONObject documentation for more details. 有关更多详细信息,请参阅JSONObject文档。

Here is an tutorial of using GSON library to achieve typed object conversion. 这是使用GSON库实现类型化对象转换的教程。

http://java.sg/parsing-a-json-string-into-an-object-with-gson-easily/ http://java.sg/parsing-a-json-string-into-an-object-with-gson-easily/

Sathishpaul is correct but just to clarify : Sathishpaul是正确的,但只是为了澄清:

JSONObject obj =  new JSONObject(YourJSONString);
Long date = obj.getLong("date");
int duration = obj.getInt("duration");

etc.. 等等..

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

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