1. 程式人生 > >Java JsonParseException異常的解決

Java JsonParseException異常的解決


在開發工作過程中,有遇到以下異常的其實是引數異常,也就是json的拼裝有問題。

在介面對接的時候,對方傳過來的json解析報錯:

org.codehaus.jackson.JsonParseException: Unexpected character ('c' (code 99)): was expecting double-quote to start field name
 at [Source: [email protected]; line: 1, column: 3] 發現對方傳過來的json串格式不對導致我解析失敗

其實對方完全可以json線上解析一下格式,導致我還得找原因。

本章的內容主要介紹的json的拼裝規則以及技巧。

JsonParseException: Unexpected character (‘=’ (code 61)): was expecting a colon to separate field name and value\n at [Source: [email protected]; line: 1, column: 23]”

首先介紹一下HTTP返回的一些異常情況。如下圖一覽表。其中標紅線的地方。json_parse異常。

Jackson 序列化

User user = new User(); 
user.setName("admin");
user.setPassword("123456");
/**
     * ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中實現。
     * ObjectMapper有多個JSON序列化的方法,可以把JSON字串儲存File、OutputStream等不同的介質中。
     * writeValue(File arg0, Object arg1)把arg1轉成json序列,並儲存到arg0檔案中。
     * writeValue(OutputStream arg0, Object arg1)把arg1轉成json序列,並儲存到arg0輸出流中。
     * writeValueAsBytes(Object arg0)把arg0轉成json序列,並把結果輸出成位元組陣列。
     * writeValueAsString(Object arg0)把arg0轉成json序列,並把結果輸出成字串。
     */ 
ObjectMapper arry = new ObjectMapper(); 
//User類轉JSON 
//輸出結果:{"name":"小民","age":20,"birthday":844099200000,"email":"

[email protected]"} 
String json = mapper.writeValueAsString(user);  
System.out.println(json);


Gson 序列化

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

JsonArray arry = new JsonArray(); 
JsonObject j = new JsonObject(); 
    j.addProperty("username", username); 
    j.addProperty("password", password); 
arry.add(j);
String json = array.toString();    //即為組裝好的json字串。


FastJson 序列化

User user = new User("testFastJson001", "maks", 105); 
String text = JSON.toJSONString(user); 
System.out.println("toJsonString()方法:text=" + text); 
// 輸出結果:text={"age":105,"id":"testFastJson001","name":"maks"}


About Me:

Github地址:https://github.com/noseparte 
Email:  [email protected]     有java與hadoop相關的技術問題,可以發私信與我交流。
NPM地址:  https://www.npmjs.com/~noseparte
WebSite: http://www.noseparte.com/   Copyright © 2017 noseparte

--------------------- 
作者:Noseparte 
來源:CSDN 
原文:https://blog.csdn.net/noseparte/article/details/78529375 
版權宣告:本文為博主原創文章,轉載請附上博文連結!