下面是测试结果{"name":"zhaokaiqiang","age":22,"person":{"name":"zhaokaiqiang","birthday":{"day":19,"month":1,"year":1992},"age":22}}
(2)Array格式
下面我们介绍如何生成Array格式的Json数据,其实和上面的差不多。
下面是代码实现:
/**
* 创建Array形式的json
*
* @throws Exception
*/
public void createArrayJson() 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.writeStartArray();
jsonGenerator.writeString("zhaokaiqiang");
jsonGenerator.writeNumber(22);
jsonGenerator.writeObject(p);
jsonGenerator.writeEndArray();
jsonGenerator.flush();
jsonGenerator.close();
Log.d(TAG, stringWriter.toString());
} 思路是完全一样的,下面是测试的结果:
["zhaokaiqiang",22,{"name":"zhaokaiqiang","birthday":{"day":19,"month":1,"year":1992},"age":22}]
下面开始介绍如何解析Json数据为Java对象。
我们直接看解析代码
public void toObject() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
Person p = new Person("zhaokaiqiang", 22, new Birthday(1992, 1, 19));
String jsonString = getJsonString(p);
Person person = objectMapper.readValue(jsonString, Person.class);
Log.d(TAG, person.toString());
}
在解析的时候,我们还是需要用ObjectMapper对象,调用readValue,然后传入需要解析的json数据和转换类型的class,就可以完成转换了。