今天用gson解析json数据的时候遇到一个奇怪的问题,虽然解决了但还是没明白是什么原因。。。
起因:客户端发送的json字符串中包含二进制数据(相当于图片),我需要把这个json解析后将数据存到hbase中去,由于发来的json字符串中有转义字符,所以我想当然的想到了gson的JsonPrimitive,可是按以前的套路却发现报这个错Caused by: com.google.gson.stream.MalformedJsonException: Expected name at line 1 column 2 path $.
最后折腾了半天才发现JsonPrimitive并没有把转义字符去掉,可是当我直接用String的时候就可以,但是当用System.in时(就相当于从客户端获取数据)却不行,我很是困惑,以下是我在Myeclipse中运行的代码:
public class Parse1 {
private String type;
public String getType() {
return type;
}
public void setProbeid(String type) {
this.type = type;
}
public Data data;
public static class Data{
public String hctx;
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import com.google.gson.Gson;
import com.google.gson.JsonPrimitive;
public class GsonTest1 {
public static void main(String[] args) throws Exception {
Gson gson=new Gson();
String hehe = "{\"type\": 1, \"data\": {\"hlen\": 42, \"hctx\": \"(Q2\\u00053?\\u0000#$???\\b\\u0000E\\u0000\\u0001\\u0001?@\\u0000@\\u0011'???f\\u001d??f\\u001f?<\\u001ea\\u0000??*\" }}";
JsonPrimitive jsonPrimitive=new JsonPrimitive(hehe);
System.out.println(jsonPrimitive.getAsString());
Parse1 p=gson.fromJson(jsonPrimitive.getAsString(), Parse1.class);
System.out.println("type:"+p.getType());
System.out.println("hctx:"+p.data.hctx);
BufferedReader wt = new BufferedReader(new InputStreamReader(System.in));
String str = wt.readLine();
JsonPrimitive jsonPrimitive1=new JsonPrimitive(str);
System.out.println(jsonPrimitive.getAsString());
Parse1 p1=gson.fromJson(jsonPrimitive1.getAsString(), Parse1.class);
System.out.println("type:"+p1.getType());
System.out.println("hctx:"+p1.data.hctx);
}
}
运行结果:
解决:不用JsonPrimitive而是直接用Java的replaceAll替代方法
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.google.gson.JsonPrimitive;
public class hehe {
public static void main(String args[]) throws IOException{
String a = "{\"type\": 1, \"data\": {\"hlen\": 42, \"hctx\": \"(Q2\\u00053?\\u0000#$???\\b\\u0000E\\u0000\\u0001\\u0001?@\\u0000@\\u0011'???f\\u001d??f\\u001f?<\\u001ea\\u0000??*\" }}";
System.out.println(a.replaceAll("\\\\\"", "\""));
JsonPrimitive jsonPrimitive=new JsonPrimitive(a);
System.out.println(jsonPrimitive.getAsString());
BufferedReader wt = new BufferedReader(new InputStreamReader(System.in));
String hui = wt.readLine();
System.out.println(hui.replaceAll("\\\\\"", "\""));
JsonPrimitive jsonPrimitive1=new JsonPrimitive(hui);
System.out.println(jsonPrimitive1.getAsString());
System.out.println(hui.replaceAll("\\\\\"", "\"").replaceAll("\\\\\\\\", "\\\\"));
}
}
运行结果: