Java JsonParseException异常的解决办法
在开发工作过程中,有遇到以下异常的其实是参数异常,也就是json的拼装有问题。本章的内容主要介绍的json的拼装规则以及技巧。
JsonParseException: U
nexpected character (‘=’ (code 61)): was expecting a colon to separate field name and value\n at [Source: java.io.BufferedInputStream@170e3f35; 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
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: noseparte@aliyun.com 有java与hadoop相关的技术问题,可以发私信与我交流。
- NPM地址: https://www.npmjs.com/~noseparte
- WebSite: http://www.noseparte.com/ Copyright © 2017 noseparte