/** * <b>function:</b>将list集合转换成json字符串 * @author hoojo * @createDate 2010-11-23 下午06:05:59 */@Testpublic void writeListJSON() { try { List<AccountBean> list = new ArrayList<AccountBean>(); list.add(bean); bean = new AccountBean(); bean.setId(2); bean.setAddress("address2"); bean.setEmail("email2"); bean.setName("haha2"); list.add(bean); System.out.println("jsonGenerator"); //list转换成JSON字符串 jsonGenerator.writeObject(list); System.out.println(); System.out.println("ObjectMapper"); //用objectMapper直接返回list转换成的JSON字符串 System.out.println("1###" + objectMapper.writeValueAsString(list)); System.out.print("2###"); //objectMapper list转换成JSON字符串 objectMapper.writeValue(System.out, list); } catch (IOException e) { e.printStackTrace(); }}
结果如下:
jsonGenerator[{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"},{"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}]ObjectMapper1###[{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"},{"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}]2###[{"address":"china-Guangzhou","name":"hoojo","id":1,"birthday":null,"email":"hoojo_@126.com"},{"address":"address2","name":"haha2","id":2,"birthday":null,"email":"email2"}]
外面就是多了个[]中括号;同样Array也可以转换,转换的JSON和上面的结果是一样的,这里就不再转换了。~.~
4、下面来看看jackson提供的一些类型,用这些类型完成json转换;如果你使用这些类型转换JSON的话,那么你即使没有JavaBean(Entity)也可以完成复杂的Java类型的JSON转换。下面用到这些类型构建一个复杂的Java对象,并完成JSON转换。
@Testpublic void writeOthersJSON() { try { String[] arr = { "a", "b", "c" }; System.out.println("jsonGenerator"); String str = "hello world jackson!"; //byte jsonGenerator.writeBinary(str.getBytes()); //boolean jsonGenerator.writeBoolean(true); //null jsonGenerator.writeNull(); //float jsonGenerator.writeNumber(2.2f); //char jsonGenerator.writeRaw("c"); //String jsonGenerator.writeRaw(str, 5, 10); //String jsonGenerator.writeRawValue(str, 5, 5); //String jsonGenerator.writeString(str); jsonGenerator.writeTree(JsonNodeFactory.instance.POJONode(str)); System.out.println(); //Object jsonGenerator.writeStartObject();//{ jsonGenerator.writeObjectFieldStart("user");//user:{ jsonGenerator.writeStringField("name", "jackson");//name:jackson jsonGenerator.writeBooleanField("sex", true);//sex:true jsonGenerator.writeNumberField("age", 22);//age:22 jsonGenerator.writeEndObject();//} jsonGenerator.writeArrayFieldStart("infos");//infos:[ jsonGenerator.writeNumber(22);//22 jsonGenerator.writeString("this is array");//this is array jsonGenerator.writeEndArray();//] jsonGenerator.writeEndObject();//} AccountBean bean = new AccountBean(); bean.setAddress("address"); bean.setEmail("email"); bean.setId(1); bean.setName("haha"); //complex Object jsonGenerator.writeStartObject();//{ jsonGenerator.writeObjectField("user", bean);//user:{bean} jsonGenerator.writeObjectField("infos", arr);//infos:[array] jsonGenerator.writeEndObject();//} } catch (Exception e) { e.printStackTrace(); }}
运行后,结果如下: