json/Gson的学习

来源:互联网 发布:zabbix windows 模板 编辑:程序博客网 时间:2024/05/22 14:49
json的基础知识
1.概念:JSON是一种与开发语言无关的、轻量级的数据格式。全称(JavaScript Object Notation)。
2.json数据格式优点:易于阅读和编写,易于程序解析与生产
3.标准的json数据表示:
  数据结构:Object  Array
  基本类型:String  number(数字型)  true  false  null(为空)
  数据结构—Object:使用花括号{}包含的键值对结构,Key必须是String类型用"",value为任何基本类型或数据结构。
 Key与value中间用冒号:隔开  例如:{StringKey1 :value1,StringKey2 :value2,...}
  数据结构—Array: 使用中括号[]来起始,并用逗号来分割元素。例如:[value1,value2,...]

java中两种常见的json处理方式:objectjson的源码地址 https://github.com/stleary/JSON-java/blob/master/JSONObject.java
(在这里如果需要添加null的数据,需要先声明null的对象 Object object=null;)
1.通过json的元素一个个添加的方法:
JsonObject jsonObject=new JsonObject();
jsonObject.put("Key",value);
jsonObject.toString();
2.通过Map容器创建json数据:
Map<String,Object> map=new HashMap<String,Object>();
map.put("Key",value);
new JsonObject(map).toString();
3.通过javabean来创建json数据;
首先构造javabean  javabean1
javabean1.set属性();   //添加数据
new JsonObject(javabean1).toString();  // 通过构造方法来构造javabean的json数据

综合运用
1.从文件中读取json数据:需要引用apache的commons-io的jar包
File file=new File(json文件地址).getFile();
String content=FileUtils.readFileToString(file);
JsonObject jsonObject=new JsonObject(content);
if(!JsonObject.isnull("name")){       //防止文件中没有元素,可以通过日志打出
jsonObject.getString("name");
}
jsonObject.getString("某个key");
JSONArray jsonarray=jsonObject.getJSONArray("某个key");






json数据格式的进阶Gson(使用前先配置Gson的pom的坐标):https://github.com/google/gson

1.Gson生成json的数据格式。满足javabean的正向生成与反向解析,
Gson gson=new Gson();
gson.toJson();

2.gson的javabean解析
Gson gson=new Gson();
类名diaosi  wangxianer=gson.fromJson(content,类名.class);
System.out.print(wangxiaoer);

3.支持个性化的转化:(例如日期类型)
Gson gson=new GsonBuilder().setDataFormat("yyyy-mm-dd").creat();
新类名diaosi1  wangxianer=gson.fromJson(content,类名diaosi1.class);
System.out.print(wangxiaoer);

4.将json的数组与java中的集合进行无缝对接:
根据javabean中的数据格式,自动匹配json文件中数组数据。

0 0
原创粉丝点击