在开发工作过程中,有遇到以下异常的其实是参数异常,也就是json的拼装有问题。
在接口对接的时候,对方传过来的json解析报错:
org.codehaus.jackson.JsonParseException: Unexpected character ('c' (code 99)): was expecting double-quote to start field name at [Source: java.io.StringReader@1c92cb31; 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: 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 //输出结果:{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"} 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"}