本文内容来自JSON快速入门(Java版)
JSON是一种与开发语言无关的、轻量级的数据格式。全称JavaScript Object Notation.
优点:易于人的阅读和编写,易于程序解析与生产
数据结构
{}
包含的键值对结构,Key必须是string类型(必须用双引号),value为任何基本类型或数据结构[]
来起始,并用逗号,来分隔元素基本类型
注意:在JSON中没有时间或日期这样的类型,也没有注释
本例子使用的是stleary/JSON-java,文档位置是http://stleary.github.io/JSON-java/index.html
Maven地址org.json
如下简单的例子,创建一个JSONObject
,可能会抛出异常JSONException
private static void JSONObject() {
JSONObject object = new JSONObject();
Object nullObj = null;
try {
object.put("name", "王小二");
object.put("age", 25.2);
object.put("birthday", "1990-01-01");
object.put("school", "蓝翔");
object.put("major", new String[] {"理发", "挖掘机"});
object.put("has_girlfriend", false);
object.put("car", nullObj);
object.put("house", nullObj);
object.put("comment", "这是一个注释");
System.out.println(object.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
控制台输出结果为:{"birthday":"1990-01-01","major":["理发","挖掘机"],"school":"蓝翔","name":"王小二","has_girlfriend":false,"comment":"这是一个注释","age":25.2}
使用HashMap
构建JSON
private static void createJsonByMap(){
Object nullObj = null;
Map<String, Object> object = new HashMap<String, Object>();
object.put("name", "王小二");
object.put("age", 25.2);
object.put("birthday", "1990-01-01");
object.put("school", "蓝翔");
object.put("major", new String[] {"理发", "挖掘机"});
object.put("has_girlfriend", false);
object.put("car", nullObj);
object.put("house", nullObj);
object.put("comment", "这是一个注释");
System.out.println(new JSONObject(object));
}
例如,创建DiaoSi
类
public class DiaoSi {
private String name;
private String school;
private boolean has_girlfriend;
private double age;
private Object car;
private Object house;
private String[] major;
private String comment;
private String birthday;
//getter setter
}
通过bean创建JSON对象:
public static void createJsonByBean() {
DiaoSi bean = new DiaoSi();
bean.setName("王小二");
bean.setAge(25.2);
bean.setBirthday("1990-01-01");
bean.setSchool("蓝翔");
bean.setMajor(new String[] {"理发", "挖掘机"});
bean.setHas_girlfriend(false);
bean.setHouse(null);
bean.setCar(null);
bean.setComment("这是一个注释");
System.out.println(new JSONObject(bean));
}
这里用到了common io
从文件中读取json,并输出
File file = new File(ReadJSONSample.class.getResource("/wangxiaoer.json").getFile());
String content = FileUtils.readFileToString(file);
JSONObject jsonObject = new JSONObject(content);
System.out.println("name : " + jsonObject.getString("name"));
System.out.println("age : " + jsonObject.getDouble("age"));
System.out.println("has_girlfriend : " + jsonObject.getBoolean("has_girlfriend"));
System.out.println("major : " + jsonObject.getJSONArray("major"));
对于Array,可以使用如下的方式:
JSONArray majorArray = jsonObject.getJSONArray("major");
for(int i=0; i < majorArray.length(); i++){
String m = (String) majorArray.get(i);
System.out.println("major-" + i + m);
}
使用isNull
来判断是否为null
if (!jsonObject.isNull("name")) {
System.out.println("name : " + jsonObject.getString("name"));
}
通过bean来创建JSON
DiaoSi bean = new DiaoSi();
bean.setName("王小二");
bean.setAge(25.2);
bean.setBirthday("1990-01-01");
bean.setSchool("蓝翔");
bean.setMajor(new String[] {"理发", "挖掘机"});
bean.setHas_girlfriend(false);
bean.setHouse(null);
bean.setCar(null);
bean.setComment("这是一个注释");
Gson gson = new Gson();
System.out.println(gson.toJson(bean));
输出结果为:{"name":"王小二","school":"蓝翔","has_girlfriend":false,"age":25.2,"major":["理发","挖掘机"],"comment":"这是一个注释","birthday":"1990-01-01"}
使用@SerializedName
改变生成JSON的key的值,例如
@SerializedName("NAME")
private String name;
则生成JSON的结果为:{"NAME":"王小二","school":"蓝翔","has_girlfriend":false,"age":25.2,"major":["理发","挖掘机"],"comment":"这是一个注释","birthday":"1990-01-01"}
GsonBuilder
在JSON构建过程中做自定义
如下美化JSON:
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setPrettyPrinting();
Gson gson = gsonBuilder.create();
System.out.println(gson.toJson(bean));
输出结果为:
{
"NAME": "王小二",
"school": "蓝翔",
"has_girlfriend": false,
"age": 25.2,
"major": [
"理发",
"挖掘机"
],
"comment": "这是一个注释",
"birthday": "1990-01-01"
}
如下,使用setFieldNamingStrategy
把age
变成大写
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setPrettyPrinting();
gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() {
public String translateName(Field f) {
if (f.getName().equals("age")) {
return "AGE";
}
return f.getName();
}
});
Gson gson = gsonBuilder.create();
System.out.println(gson.toJson(bean));
输出结果为:
{
"NAME": "王小二",
"school": "蓝翔",
"has_girlfriend": false,
"AGE": 25.2,
"major": [
"理发",
"挖掘机"
],
"comment": "这是一个注释",
"birthday": "1990-01-01"
}
如果有些属性不想暴露,可以使用transient
,表示在JSON生成过程中忽略掉该属性
private transient String ignore;
从文件中读取json,并转换为一个bean
File file = new File(ReadJSONSample.class.getResource("/wangxiaoer.json").getFile());
String content = FileUtils.readFileToString(file);
Gson gson = new Gson();
DiaoSi bean = gson.fromJson(content, DiaoSi.class);
System.out.println(bean);
File file = new File(ReadJSONSample.class.getResource("/wangxiaoer.json").getFile());
String content = FileUtils.readFileToString(file);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
DiaoSiWithBirthday bean = gson.fromJson(content, DiaoSiWithBirthday.class);
System.out.println(bean);
输出结果:DiaoSi [name=王小二, school=蓝翔, has_girlfriend=false, age=25.2, car=null, house=null, major=[理发, 挖掘机], comment=这是一个注释, birthday=Mon Jan 01 00:00:00 CST 1990]
json数组转为对象数组
参考GSON turn an array of data objects into json - Android
import com.google.gson.Gson;
import java.util.List;
import java.util.ArrayList;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
public class Test {
public static void main (String[] args) {
// Initialize a list of type DataObject
List<DataObject> objList = new ArrayList<DataObject>();
objList.add(new DataObject(0, "zero"));
objList.add(new DataObject(1, "one"));
objList.add(new DataObject(2, "two"));
// Convert the object to a JSON string
String json = new Gson().toJson(objList);
System.out.println(json);
// Now convert the JSON string back to your java object
Type type = new TypeToken<List<DataObject>>(){}.getType();
List<DataObject> inpList = new Gson().fromJson(json, type);
for (int i=0;i<inpList.size();i++) {
DataObject x = inpList.get(i);
System.out.println(x);
}
}
private static class DataObject {
private int a;
private String b;
public DataObject(int a, String b) {
this.a = a;
this.b = b;
}
public String toString() {
return "a = " +a+ ", b = " +b;
}
}
}
JSON是Android SDK官方的库
GSON适用于服务端开服,GSON比JSON功能更强大。