简体   繁体   English

用JAVA写json字符串

[英]write json string in JAVA

I am using json developing android sdk. 我正在使用json开发android sdk。 I found writing json string is annoying, take a look: 我发现写json字符串很烦人,看看:

post_my_server("{\"cmd\":\"new_comment\"}");

I need to manually escape quotes, is there any clean way to do this? 我需要手动转义引号,是否有任何干净的方法可以做到这一点?

You can use single quotes "{'cmd':'new_comment'}". 您可以使用单引号“ {'cmd':'new_comment'}”。

Alternatively, there is free code at http://json.org/java/ for implementing JSON at an object level. 另外, http://json.org/java/上有免费的代码可用于在对象级别实现JSON。 It's free as in very permissive, I am no lawyer, but it would seem that the only stipulation is that the software you include it in is good, and not evil. 它是免费的,因为它是非常宽松的,我不是律师,但是似乎唯一的规定是,包含在其中的软件是好的,而不是邪恶的。

To create json string use jackson core jars. The code snippet to generate a sample json string ,

JsonFactory jFactory = new JsonFactory();
StringWriter writer = new StringWriter();
/*** write to string ***/
JsonGenerator jsonGenerator = jFactory.createJsonGenerator(writer);
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("company", [Value]);
jsonGenerator.writeNumberField("salary", [value]); 
jsonGenerator.writeEndObject();
jsonGenerator.close();
String jsonString = writer.toString();

I use the jackson json parsers and serializers , they are completely self contained, and allow for reading, writing of any java object to and from json. 我使用杰克逊json解析器和序列化器,它们完全独立,并且允许在json中读写任何java对象。

Assume you have a file called "user.json" which contains a big json in it.... 假设您有一个名为“ user.json”的文件,其中包含一个大json。

private static void convert(){ Map<String,Object> userData = mapper.readValue(new File("user.json"), Map.class); }

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

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