下面是测试代码和测试结果
/**
* 集合对象
*
* @throws Exception
*/
public void objectsToJson() throws Exception {
Person p = new Person("zhaokaiqiang", 22, new Birthday(1992, 1, 19));
ArrayList<Person> persons = new ArrayList<Person>();
persons.add(p);
persons.add(p);
persons.add(p);
Log.d(TAG, getJsonString(persons));
}
/**
* 单一对象
*
* @throws Exception
*/
public void objectToJson() throws Exception {
Person p = new Person("zhaokaiqiang", 22, new Birthday(1992, 1, 19));
Log.d(TAG, getJsonString(p));
}
测试结果如下
{"name":"zhaokaiqiang","birthday":{"day":19,"month":1,"year":1992},"age":22}
[{"name":"zhaokaiqiang","birthday":{"day":19,"month":1,"year":1992},"age":22},{"name":"zhaokaiqiang","birthday":{"day":19,"month":1,"year":1992},"age":22},{"name":"zhaokaiqiang","birthday":{"day":19,"month":1,"year":1992},"age":22}]
这里所说的复杂对象指的是由多种不同数据类型的数据组成的数据,下面我们将介绍如何创建这种复杂对象的Json数据。
我们在前面介绍过,Json格式分为Object形式和Array形式,我们将分别介绍这两种格式如何生成。
(1)Object格式
我们先直接看下面的代码吧!
/**
* 生成Object形式的json
*
* @throws Exception
*/
public void createObjectJson() throws Exception {
Person p = new Person("zhaokaiqiang", 22, new Birthday(1992, 1, 19));
StringWriter stringWriter = new StringWriter();
// 必须通过这种方式获取
JsonGenerator jsonGenerator = JacksonMapper.getInstance()
.getJsonFactory().createJsonGenerator(stringWriter);
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField("name", "zhaokaiqiang");
jsonGenerator.writeNumberField("age", 22);
jsonGenerator.writeObjectField("person", p);
jsonGenerator.writeEndObject();
jsonGenerator.flush();
jsonGenerator.close();
Log.d(TAG, stringWriter.toString());
}
JsonGenerator是一个生成器,如果我们想创建复杂的Json对象,我们就可以是用这个类来完成。但是有一点必须要注意,就是获取JsonGenerator的方式,我们必须使用ObjectMapper的getJsonFactory(),然后创建一个JsonGenerator,否则如果我们使用writeObjectField()方法的时候,会报下面的异常
java.lang.IllegalStateException: No ObjectCodec defined for the generator, can only serialize simple wrapper types (type passed com.example.jsondemo.Person)
上面的其余代码很简单,只要根据不同的数据类型,调用对应的write___Field()即可。