json相关

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>>(){});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值