jar:Gson.jar
工具类
package json;
import java.lang.reflect.Type;
import com.google.gson.Gson;
public class GsonUtil {
private static Gson gson = new Gson();
public static String toJson(Object obj, Type type) {
return gson.toJson(obj, type);
}
public static Object fromJson(String str,Type type){
return gson.fromJson(str, type);
}
}
测试类
package json.test;
import json.GsonUtil;
public class Man {
String name;
String phone;
public Man() {
super();
}
public Man(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((phone == null) ? 0 : phone.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Man other = (Man) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (phone == null) {
if (other.phone != null)
return false;
} else if (!phone.equals(other.phone))
return false;
return true;
}
public String toString() {
return GsonUtil.toJson(this, Man.class);
}
}
测试执行类
package json.test;
public class TestGson {
public static void main(String[] args) {
Man man = new Man("aa","123");
System.out.println(man.toString());
}
}