简体   繁体   中英

write json string in JAVA

I am using json developing android sdk. I found writing json string is annoying, take a look:

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'}".

Alternatively, there is free code at http://json.org/java/ for implementing JSON at an object level. 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.

Assume you have a file called "user.json" which contains a big json in it....

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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