如何使用Jackson创建这个json字符串? [英] How to create this json string using Jackson?
本文介绍了如何使用Jackson创建这个json字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我想要的输出
{"node":{"type":"community","field_incentives":{"und":[{"value":"fun"},{"value":"nice"}]},"field_community_email":{"und":[{"value":"some@one.com"}]}}}
这是我的代码,但似乎没有生成上面的输出。如果有更好更简单的方法,请告诉我。谢谢
Here's my code but it does not seem to generate the output above. If there's a better and simpler way to do this, please let me know. Thanks
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JsonFactory f = new JsonFactory();
JsonGenerator g = f.createJsonGenerator(outputStream);
g.writeStartObject();
g.writeObjectFieldStart("node");
g.writeStringField("type", "community");
g.writeObjectFieldStart("field_incentives");
g.writeFieldName("und");
g.writeStartArray();
???I don't know how to make [{"value":"fun"},{"value":"nice"}]
g.writeEndArray();
g.writeEndObject();
g.close();
推荐答案
我只是逐行写入你的输出json文件参考JsonGenerator 。希望它会有所帮助。
I simply write line by line to your output json file Reference JsonGenerator. Hope it will help.
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.JsonMappingException;
public class CopyOfJacksonStreamExample {
public static void main(String[] args) {
try {
JsonFactory jfactory = new JsonFactory();
/*** write to file ***/
JsonGenerator jGenerator = jfactory.createJsonGenerator(new File(
"c:\\user.json"), JsonEncoding.UTF8);
jGenerator.writeStartObject(); // {
jGenerator.writeObjectFieldStart("node"); // node: {
jGenerator.writeStringField("type", "community"); // "type" : "community"
jGenerator.writeObjectFieldStart("field_incentives"); // "field_incentives" : {
jGenerator.writeFieldName("und"); // "und" :
jGenerator.writeStartArray(); // [
jGenerator.writeStartObject(); // {
jGenerator.writeStringField("value", "fun"); // "value" : "fun"
jGenerator.writeStringField("value", "nice"); // "value" : "nice"
jGenerator.writeEndObject(); // }
jGenerator.writeEndArray(); // ]
jGenerator.writeEndObject(); // } end of field_incentives
jGenerator.writeObjectFieldStart("field_community_email"); // "field_community_email" : {
jGenerator.writeFieldName("und"); // "und" :
jGenerator.writeStartArray(); // [
jGenerator.writeStartObject(); // {
jGenerator.writeStringField("value", "some@one.com"); // "value" : "fun"
jGenerator.writeEndObject(); // }
jGenerator.writeEndArray(); // ]
jGenerator.writeEndObject(); // } end of field_community_email
jGenerator.writeEndObject(); // } end of node
jGenerator.writeEndObject(); // }
jGenerator.close();
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这篇关于如何使用Jackson创建这个json字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文