1、什么是json
Json是一种与开发语言无关的,轻量级的数据格式。全称JavaScript Object Notation。
2、json数据类型
数据结构: Object ,Array
基本类型: String,number,true,false,null
Object:使用花括号{}包含的键值对结构,key必须是String类型,value为任何基本类型或者数据结构。
Array:使用中括号[]来起始,并用逗号,号分割元素。
3、常用json api
3.1、JSONObject
创建json
直接创建JsonObject对象:
JSONObject jsonObject = new JSONObject(); json.put(“key”, value);
创建HashMap:
Map<String, Object> map = new HashMap<String, Object>();
map.put(“key”,value);
JSONObject jsonObject = new JSONObject(map);
创建JavaBean:
X x = new ();
x.setY(value);
JSONObject json = new JSONObject(X);
解析json
读取文件内容,String类型转为JSONObject类型,
JSONObject json = new JSONObject(jsonString);
json.getString(“key”);
数组类型的需要使用JSONArray:JSONArray jsonArray = josn.getJSONArray(“key”);循环遍历,可以拿到数组类型。
3.2、Gson
创建gson
直接创建Gson对象:
Gson gson = new Gson (new X());
使用GsonBuilder:
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
解析gson
从文件读取json格式的数据:
File file = new File(ReadJSONSample.class.getResource(“X.json”)).getFile();
String content = FileUtils.readFileToString(file);
解析:
Gson gson = new Gson();
X x = gson.fromJson(content, X.class);
技巧:
@SerializedName(“NAME”):key转为NAME;
gsonBuilder.setPrettyPrinting():格式化打印json;
transient:在属性前面加上该关键字,可以不输出该属性。
3.3、FastJson
创建json
String json = JSON.toJSONString(new X());
解析json
X x = JSON.parseObject(json, X.class);
List<String> list = JSON.parseArray(json, String.class);
3.4、JackSon
创建json
ObjectMapper om = new ObjectMapper();
String json = om.writeValueAsString(new X());
解析json
ObjectMapper om = new ObjectMapper();
X x = om.readValue(json, X.class);
ArrayList<String> list = om.readValue(json, new TypeReference<ArrayList<String>>(){});