初学Json
在今天初学Json,以前一直不懂JsonArray和JonObject是什么,一直以为是方法,今天看资料,了解是一个Java对象
1,JSONObject
json对象,就是一个键对应一个值,使用的是大括号{ },如:{key:value}
2,JSONArray
json数组,使用中括号[ ],只不过数组里面的项也是json键值对格式的
Json对象中添加的是键值对,JSONArray中添加的是Json对象
JSONArray getJsonArray=JSONArray.fromObject(arrayStr);//将结果转换成JSONArray对象的形式
JSONObject getJsonObj = getJsonArray.getJSONObject(0);//获取json数组中的第一项
String result=getJsonObj.getJSONObject("name1").getJSONObject("name2").getJSONObject("name4");
JSONObject Json = new JSONObject();
JSONArray JsonArray = new JSONArray();
Json.put("key", "value");//JSONObject对象中添加键值对
JsonArray.add(Json);//将JSONObject对象添加到Json数组中
使用gson
gosn是什么?
gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。
gson的初步使用
package org.gson.main;
import com.google.gson.Gson;
public class test {
public static void main(String[] args) {
Gson gson = new Gson();
int[] ints = {1, 2, 3, 4, 5};
String[] strings = {"abc", "def", "ghi"};
System.out.println(gson.toJson(ints));
System.out.println(gson.toJson(strings));
}
}
输出结果:
[1,2,3,4,5]
[“abc”,”def”,”ghi”]
gson的进阶应用
//注意这里的Gson的构建方式为GsonBuilder,区别于test1中的Gson gson = new Gson();
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation() //不导出实体中没有用@Expose注解的属性
.enableComplexMapKeySerialization() //支持Map的key为复杂对象的形式
.serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss:SSS")//时间转化为特定格式
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)//会把字段首字母大写,注:对于实体上使用了@SerializedName注解的不会生效.
.setPrettyPrinting() //对json结果格式化.
.setVersion(1.0) //有的字段不是一开始就有的,会随着版本的升级添加进来,那么在进行序列化和返序列化的时候就会根据版本号来选择是否要序列化.
//@Since(版本号)能完美地实现这个功能.还的字段可能,随着版本的升级而删除,那么
//@Until(版本号)也能实现这个功能,GsonBuilder.setVersion(double)方法需要调用.
.create();