google gson 是一个非常轻量的java 对象与json相互转化工具。
入门也非常简单,下面来看几种常用的方法
public class Pet{ private String ma; private String ses; private String add; private String oct; private Listmanagers = new ArrayList (); //get set }
以此pet类作为例子
Gson g = new Gson(); String json = g.toJson(p); Pet pt= g.fromJson(json, Pet.class);
1 隐藏某个字段
当然还有特殊要求,必须pet 转化json 所有字段都转化了,现在是隐藏某个字段,很简单,只需使用annotation @Expos 暴露出来就行,需要的加上,不需要的不加
@Expose private String ma; @Expose() private String ses; @Expose() private String add; private String oct;
这是gson 就应该这么new
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); System.out.println(gson.toJson(p)); System.out.println(gson.toJson(oList));
2 换属性名字
public class SomeClassWithFields { @SerializedName("name") private final String someField; private final String someOtherField; public SomeClassWithFields(String a, String b) { this.someField = a; this.someOtherField = b; } } //The following shows the output that is generated when serializing an instance of the above example class: SomeClassWithFields objectToSerialize = new SomeClassWithFields("a", "b"); Gson gson = new Gson(); String jsonRepresentation = gson.toJson(objectToSerialize); System.out.println(jsonRepresentation); ===== OUTPUT ===== {"name":"a","someOtherField":"b"}
3 加版本号
public class User { private String firstName; private String lastName; @Since(1.0) private String emailAddress; @Since(1.0) private String password; @Since(1.1) private Address address; }
4 InputStream 转 json
public ListreadJsonStream(InputStream in) throws IOException { JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); try { return readMessagesArray(reader); } finally { reader.close(); } } public List readMessagesArray(JsonReader reader) throws IOException { List messages = new ArrayList (); reader.beginArray(); while (reader.hasNext()) { messages.add(readMessage(reader)); } reader.endArray(); return messages; } public Message readMessage(JsonReader reader) throws IOException { long id = -1; String text = null; User user = null; List geo = null; reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("id")) { id = reader.nextLong(); } else if (name.equals("text")) { text = reader.nextString(); } else if (name.equals("geo") && reader.peek() != JsonToken.NULL) { geo = readDoublesArray(reader); } else if (name.equals("user")) { user = readUser(reader); } else { reader.skipValue(); } } reader.endObject(); return new Message(id, text, user, geo); } public List readDoublesArray(JsonReader reader) throws IOException { List doubles = new ArrayList (); reader.beginArray(); while (reader.hasNext()) { doubles.add(reader.nextDouble()); } reader.endArray(); return doubles; } public User readUser(JsonReader reader) throws IOException { String username = null; int followersCount = -1; reader.beginObject(); while (reader.hasNext()) { String name = reader.nextName(); if (name.equals("name")) { username = reader.nextString(); } else if (name.equals("followers_count")) { followersCount = reader.nextInt(); } else { reader.skipValue(); } } reader.endObject(); return new User(username, followersCount); }
更多功能请访问http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html 上面代码例子也有的是来自api,api非常详细。
对ztree 里面复杂的json 格式转化非常简单。
补充:使用的hibernate的项目 中经常会出现级联对象中,外键对象无法转化出来,或转出来后为null 的现像。例如:
*/ @RequestMapping(value = "/getTopicByBroad/{broadId}/{pageIndex}/{pageSize}" , produces = "text/plain;charset=UTF-8") @ResponseBody public String getTopicByBroad(@PathVariable int broadId,@PathVariable int pageIndex,@PathVariable int pageSize) { Pagetopics = topicService.getTopicByBroad(pageIndex, pageSize, broadId); List ts = topics.getResult(); //此for循环中,对象是有值的, for (Topic topic : ts) { Broad b = topic.getBroad(); System.out.println(b.getBroadName()); } Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); String json = gson.toJson(topics.getResult().get(0).getBroad()); System.out.println(json);//broad:{},user:{}无值 return json; }
其实原因很简单,因为hibernate 默认配置了懒加载,
@ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "user_id") public TtUser getTtUser() { return this.ttUser; } public void setTtUser(TtUser ttUser) { this.ttUser = ttUser; } //改成eager @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "broad_id") public Broad getBroad() { return this.broad; } 改成饥饿就行了