如何使用JSON和GSON
说明:本项目是在MyEclipse中创建Maven项目来进行对于json格式文件的操作
在maven项目中引入对于支持json开发的的依赖,在pom.xml文件中添加一下依赖: <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20090211</version> </dependency>
1. JSON使用指南
**使用jsonobject的原生的方法生成一个jsonobject**
----------
<1>创建一个jsonobject对象 JSONObject wamgxiaoer = new JSONObject(); <2>使用键值对对的形式添加对象的一些属性 Object nullobj = null; wamgxiaoer.put("name", "王小二"); wamgxiaoer.put("age", 25.2); wamgxiaoer.put("birthday", "1990-01-01"); wamgxiaoer.put("schooll", "蓝翔"); wamgxiaoer.put("major",new String[]{"理发","挖掘机"}); wamgxiaoer.put("has_girfriend", false); wamgxiaoer.put("car", nullobj); wamgxiaoer.put("house", nullobj); wamgxiaoer.put("comment", "这是一个注释");
//使用tostring方法将json格式的数据转化成一个string类型的数据进行输出
System.out.println(wamgxiaoer.toString());
使用Map方式生成jsonobject对象
<1>生成一个map类型的对象
Map<String, Object> wamgxiaoer = new HashMap<String, Object>();
Object nullobj = null; wamgxiaoer.put("name", "王小二"); wamgxiaoer.put("age", 25.2); wamgxiaoer.put("birthday", "1990-01-01"); wamgxiaoer.put("schooll", "蓝翔"); wamgxiaoer.put("major",new String[]{"理发","挖掘机"}); wamgxiaoer.put("has_girfriend", false); wamgxiaoer.put("car", nullobj); wamgxiaoer.put("house", nullobj); wamgxiaoer.put("comment", "这是一个注释");
使用jsonobject的tomap方法讲一个map类型的对象转换成一个jsonobject对象,最后利用jsonobject对象的tostring方法转换成一个字符类型数据
System.out.println(new JSONObject(wamgxiaoer).toString());
使用Java Bean方法构建json
<1>创建一个Java bean
package bean; import java.util.Arrays; import com.google.gson.annotations.SerializedName; public class Diaosi { // @SerializedName("NAME") private String name; private String school; private boolean has_girlfriend; private double age; private Object car; private Object house; private String[] major; private String coment; private String birthday; private transient String ignore; public String getIgnore() { return ignore; } public void setIgnore(String ignore) { this.ignore = ignore; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } public boolean isHas_girlfriend() { return has_girlfriend; } public void setHas_girlfriend(boolean has_girlfriend) { this.has_girlfriend = has_girlfriend; } public double getAge() { return age; } public void setAge(double age) { this.age = age; } public Object getCar() { return car; } public void setCar(Object car) { this.car = car; } public Object getHouse() { return house; } public void setHouse(Object house) { this.house = house; } public String[] getMajor() { return major; } public void setMajor(String[] major) { this.major = major; } public String getComent() { return coment; } public void setComent(String coment) { this.coment = coment; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } @Override public String toString() { return "Diaosi [name=" + name + ", school=" + school + ", has_girlfriend=" + has_girlfriend + ", age=" + age + ", car=" + car + ", house=" + house + ", major=" + Arrays.toString(major) + ", coment=" + coment + ", birthday=" + birthday + "]"; } }
<2>使用自己创建的Java bean的方法来设定属性
private static void creatByJavaBean() { Diaosi wamgxiaoer = new Diaosi(); wamgxiaoer.setName("王小二"); wamgxiaoer.setAge(25.2); wamgxiaoer.setBirthday("1990-01-01"); wamgxiaoer.setSchool("蓝翔"); wamgxiaoer.setMajor(new String[]{"理发","挖掘机"}); wamgxiaoer.setHas_girlfriend(false); wamgxiaoer.setCar(null); wamgxiaoer.setHouse(null); wamgxiaoer.setComent("这是一个注释"); System.out.println(new JSONObject(wamgxiaoer)); }
从文件解析json对象
<1>首先在pom.xml文件引入Commons-io来使用一些对于文件的操作,例如:
<dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
<2>获取json文件所在的路径从而获取一个文件对象
File file = new File(ReadJsonSample.class.getResource("/wangxiaoer.json").getFile());
<3>获取文件中的内容:
String content = FileUtils.readFileToString(file);
<4>创建一个jsonobject对象来解析json格式的数据
JSONObject jsonObject = new JSONObject(content);
<5>通过json的方法来获取一些属性对于的值
if(!jsonObject.isNull("name")){ System.out.println("姓名是:"+jsonObject.getString("name")); } if(!jsonObject.isNull("nickname")){ System.out.println("姓名是:"+jsonObject.getString("nickname")); } System.out.println("年龄是:"+jsonObject.getDouble("age")); System.out.println("是否有女朋友:"+jsonObject.getBoolean("has_girlfriend")); JSONArray majorArray = jsonObject.getJSONArray("major"); for(int i = 0;i<majorArray.length();i++){ String m = (String)majorArray.get(i); System.out.println("专业-"+(i+1)+":"+m); }
2..GSON使用指南
GSON是由谷歌公司提出来的出来json格式数据的方法
<2>引入关于GSON的依赖
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.2</version> </dependency>
<3>创建一个类的实例并为其赋值
Diaosi wamgxiaoer = new Diaosi();
wamgxiaoer.setName("王小二"); wamgxiaoer.setAge(25.2); wamgxiaoer.setBirthday("1990-01-01"); wamgxiaoer.setSchool("蓝翔"); wamgxiaoer.setMajor(new String[]{"理发","挖掘机"}); wamgxiaoer.setHas_girlfriend(false); wamgxiaoer.setCar(null); wamgxiaoer.setHouse(null); wamgxiaoer.setComent("这是一个注释"); wamgxiaoer.setIgnore("不要看见我!");
<4>创建一个GSON对象
Gson gson = new Gson();
<5>使用GSON对象的tostring方法将其转换成一个string类型的对象
System.out.println(gson.toJson(wamgxiaoer));
<6>GSONbuilder创建个性化的json格式的数据,并通过gsonbuilder的create方法来创建一个gson对象
GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setPrettyPrinting(); gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() { public String translateName(Field f) { if(f.getName().equals("name")){ return "NAME"; } return f.getName(); } }); Gson gson = gsonBuilder.create(); System.out.println(gson.toJson(wamgxiaoer)); }
GSON解析json格式数据
<1>获取json的数据文件内容
File file = new File(ReadJsonSample.class.getResource("/wangxiaoer.json").getFile()); String content = FileUtils.readFileToString(file);
<2>创建一个GSON对象
Gson gson =new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
<3>使用GSON进行反解析
Gson gson =new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
DiaosiWithBirthday wangxiaoer = gson.fromJson(content, DiaosiWithBirthday.class); System.out.println(wangxiaoer.getBirthday().toLocaleString()); System.out.println(wangxiaoer.getMajor()); System.out.println(wangxiaoer.getMajor().getClass());
想了解更多关于GSON的可以在GitHub上查看GSON的官方文档,最后附上项目的下载地址:
链接:http://pan.baidu.com/s/1pLHp5ph 密码:khbb