json与java实体类的相互转换

来源:互联网 发布:淘宝天猫内部优惠券网 编辑:程序博客网 时间:2024/06/05 06:57

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。常用与前台交互使用,在使用中有时也会碰到java与Json相互转化的情况,如下:

注意使用前要导入相关的json包

定义实体类:

/**
* 内部类
* @author Administrator
*
*/
public static class Test{
private String name;
private String word;
private String color;
private String image;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}

/**
* Json转Java类
* @param String Json
* @throws IOException
* @throws JsonMappingException
* @throws JsonParseException
*/
public Test JsonToClass(String json) throws JsonParseException, JsonMappingException, IOException{
JSONObject jsonObj=JSONObject.fromObject(json);
System.out.println("JSON获取对象:"+jsonObj.get("name"));

//两种方式均可

Test test=(Test)JSONObject.toBean(jsonObj, Test.class);
Test test=mapper.readValue(json, Test.class);
return test;
}

/**
* java类转Json
* @param class
*/
public String ClassToJson(Object test){ 

//两种方式均可
return JSONSerializer.toJSON(test).toString();
return JSONObject.fromObject(test).toString();
}

LIst与Json的转换可以参考上述方法,将list拆分成实体进行转换,也可参考相关集成的类包。

0 0
原创粉丝点击