java 用JAVA写json字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7681938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 20:57:39  来源:igfitidea点击:

write json string in JAVA

javajson

提问by Bin Chen

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

我正在使用 json 开发 android sdk。我发现写json字符串很烦人,看看:

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

I need to manually escape quotes, is there any clean way to do this?

我需要手动转义引号,有没有干净的方法来做到这一点?

回答by rp.

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. 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.

或者,http://json.org/java/ 上有免费代码用于在对象级别实现 JSON。它是免费的,因为非常宽松,我不是律师,但似乎唯一的规定是您包含它的软件是好的,而不是邪恶的。

回答by jayunit100

I use the Hymanson json parsers and serializers , they are completely self contained, and allow for reading, writing of any java object to and from json.

我使用 Hymanson 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); }

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

回答by Prakhyat

To create json string use Hymanson 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();