Json的FastJson与Jackson,2021腾讯Java面试题精选

1.JSON:fastJson的解析器,用于JSON格式字符串与JSON对象及javaBean之间的转换

2.JSONObject:fastJson提供的json对象

3.JSONArray:fastJson提供json数组对象;

FastJson的用法


首先定义三个json格式的字符串

//json字符串-简单对象型

private static final String JSON_OBJ_STR = “{“studentName”:“lily”,“studentAge”:12}”;

//json字符串-数组类型

private static final String JSON_ARRAY_STR = “[{“studentName”:“lily”,“studentAge”:12},{“studentName”:“lucy”,“studentAge”:15}]”;

//复杂格式json字符串

private static final String COMPLEX_JSON_STR = “{“teacherName”:“crystall”,“teacherAge”:27,“course”:{“courseName”:“english”,“code”:1270},“students”:[{“studentName”:“lily”,“studentAge”:12},{“studentName”:“lucy”,“studentAge”:15}]}”;

JSON格式字符串与JSON对象之间的转换

  1. json字符串-简单对象型与JSONObject之间的转换

/**

  • json字符串-简单对象型到JSONObject的转换

*/

@Test

public void testJSONStrToJSONObject() {

JSONObject jsonObject = JSONObject.parseObject(JSON_OBJ_STR);

System.out.println("studentName: " + jsonObject.getString(“studentName”) + “:” + " studentAge: "

  • jsonObject.getInteger(“studentAge”));

}

/**

  • JSONObject到json字符串-简单对象型的转换

*/

@Test

public void testJSONObjectToJSONStr() {

//已知JSONObject,目标要转换为json字符串

JSONObject jsonObject = JSONObject.parseObject(JSON_OBJ_STR);

// 第一种方式

String jsonString = JSONObject.toJSONString(jsonObject);

// 第二种方式

//String jsonString = jsonObject.toJSONString();

System.out.println(jsonString);

}

  1. json字符串(数组类型)与JSONArray之间的转换

/**

  • json字符串-数组类型到JSONArray的转换

*/

@Test

public void testJSONStrToJSONArray() {

JSONArray jsonArray = JSONArray.parseArray(JSON_ARRAY_STR);

//遍历方式1

int size = jsonArray.size();

for (int i = 0; i < size; i++) {

JSONObject jsonObject = jsonArray.getJSONObject(i);

System.out.println("studentName: " + jsonObject.getString(“studentName”) + “:” + " studentAge: "</

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值