Java进阶-操作Json数据


 
 

Json简介

JSON 是一种文本形式的数据交换格式,它比XML更轻量、比二进制容易阅读和编写,调式也更加方便;解析和生成的方式很多,Java中最常用的类库有:JSON-Java、Gson、Jackson、FastJson等

需要注意的一点:json同级别的最后一个元素后不加逗号,

本文以Gson为例,介绍操作Json数据的方法。

[] 中间 代表是一个数组
{} 中间 是一个对象
"key" : "Value" 代表一个键值对
Json数据:主要以以{} 和键值对组成
{
 
 "resultcode": "200",
 
 "reason": "successed!",
 
 "result": {
 
  "today": {
 
   "temperature": "16℃~27℃",
 
   "weather": "阴转多云",
 
   "wind": "西南风3-4 级",
 
   "week": "星期四"
  },
  
 
  "future": [
 
   {
 
    "temperature": "16℃~27℃",
 
    "weather": "阴转多云",
 
    "wind": "西南风3-4 级",
 
    "week": "星期四",
 
    "date": "20150604"
 
   },
 
 
   {
 
    "temperature": "23℃~35℃",
 
    "weather": "多云转阴",

    "wind": "西南风3-4 级",
 
    "week": "星期六",
 
    "date": "20150606"
 
   },

 
   {
 
    "temperature": "20℃~33℃",
 
    "weather": "多云",
 
    "wind": "北风微风",
 
    "week": "星期日",
 
    "date": "20150607"
 
   }
 

 
  ]
 
 },
 
 "error_code": 0
 
}

 
 

解析Json

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.google.gson.JsonIOException;
 
import java.io.FileNotFoundException;
import java.io.FileReader;
 
public class ReadJson {
 public static void main(String []args) {
  JsonParser parse = new JsonParser();
  try {
 // 初始化json文件
   JsonObject json = (JsonObject) parse.parse(new FileReader("weather.json"));
 
 //获取并输出键值对
   System.out.println("resultcode:" + json.get("resultcode").getAsInt());
   System.out.println("reason:" + json.get("reason").getAsString());

//获取并Json对象,再获取Json对象内的键值对
   JsonObject result = json.get("result").getAsJsonObject();
   JsonObject today = result.get("today").getAsJsonObject();
   System.out.println("weak:" + today.get("week").getAsString());
   System.out.println("weather:" + today.get("weather").getAsString());
   
  } catch (JsonIOException e) {
   e.printStackTrace();
  } catch (NullPointerException e) {
   e.printStackTrace();
  } catch (JsonSyntaxException e){
   e.printStackTrace();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
 }
}

在这里插入图片描述

 
 

解析JsonArray[]

import com.google.gson.JsonParser;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.google.gson.JsonIOException;
 
import java.io.FileNotFoundException;
import java.io.FileReader;
 
public class ReadJsonArray {
 public static void main(String []args) {
  JsonParser parse = new JsonParser();
  try {
//得到JsonArray : futureArray 
   JsonObject json = (JsonObject)parse.parse(new FileReader("weather.json"));
   JsonObject result = json.get("result").getAsJsonObject();
   JsonArray futureArray = result.get("future").getAsJsonArray();
   
   for (int i = 0; i < futureArray.size(); ++i) {
    JsonObject subObj = futureArray.get(i).getAsJsonObject();
    System.out.println("------");
    System.out.println("week:" + subObj.get("week").getAsString());
    System.out.println("weather:" + subObj.get("weather").getAsString());
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (JsonIOException e) {
   e.printStackTrace();
  } catch (JsonSyntaxException e) {
   e.printStackTrace();
  }
 }
}

注意:文件路径相对路径是从工程根目录开始

在这里插入图片描述

FastJson

fastjson.jar是阿里开发的一款专门用于Java开发的包,可以方便的实现json对象与JavaBean对象的转换,实现JavaBean对象与json字符串的转换,实现json对象与json字符串的转换。实现json的转换方法很多,最后的实现结果都是一样的。

pom依赖:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.60</version>
</dependency>

防止中文乱码: 在SpringMVC配置文件中更改 <mvc:annotation-driven/>

    <mvc:annotation-driven>
        <!--当仅仅传递字符串到前端时,设置数据格式-->
        <!--为返回加入响应头    Content-Type: text/html;charset=UTF-8   -->
        <!--相同方式是 @RequestMapping(value = "/b",produces="text/html;charset=UTF-8") -->
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <constructor-arg value="UTF-8"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

常用方法

        System.out.println("*******Java对象 转 JSON字符串*******");
        String str1 = JSON.toJSONString(list);
        System.out.println("JSON.toJSONString(list)==>"+str1);
        String str2 = JSON.toJSONString(user1);
        System.out.println("JSON.toJSONString(user1)==>"+str2);

        System.out.println("\n****** JSON字符串 转 Java对象*******");
        User jp_user1 = JSON.parseObject(str2,User.class);
        System.out.println("JSON.parseObject(str2,User.class)==>"+jp_user1);

        System.out.println("\n****** Java对象 转 JSON对象 ******");
        JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2);
        System.out.println("(JSONObject) JSON.toJSON(user2)==>"+jsonObject1.getString("name"));

        System.out.println("\n****** JSON对象 转 Java对象 ******");
        User to_java_user = JSON.toJavaObject(jsonObject1, User.class);
        System.out.println("JSON.toJavaObject(jsonObject1, User.class)==>"+to_java_user);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值