[英]Converting byte[] to json and vice versa without jackson or gson
I have a legacy application which has been built with java 1.5, I need a conversion between byte[] and json but I cannot use jackson or gson, because they are in a higher version of java.我有一个用 java 1.5 构建的遗留应用程序,我需要在 byte[] 和 json 之间进行转换,但我不能使用 jackson 或 gson,因为它们使用更高版本的 java。 I have methods like these and I couldn't find a way to implement with JSONObject :
我有这样的方法,但找不到使用JSONObject实现的方法:
public <T> T toObj(byte[] bytes, Class<T> responseType) {
}
If it would be so easy, then Jackson
or Gson
was never be born.如果真的那么容易,那么
Jackson
或Gson
就永远不会出生了。
I am affraid, that you have to declared deserializer for all of your objects manualy.我很害怕,您必须手动为所有对象声明反序列化器。 This is not a rocket science, but it takes time to do it.
这不是火箭科学,但需要时间来完成。 This is an example:
这是一个例子:
public static void main(String[] args) {
Data data = new Data(11, 12);
String json = toJson(data);
System.out.println(json);
byte[] bytes = json.getBytes(StandardCharsets.UTF_8);
Data res = toDataObj(bytes);
System.out.println(res.a);
System.out.println(res.b);
}
public static String toJson(Data data) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("a", data.a);
jsonObj.put("b", data.b);
return jsonObj.toString();
}
public static Data toDataObj(byte[] bytesClass) {
JSONObject jsonObject = new JSONObject(new String(bytesClass, StandardCharsets.UTF_8));
Data data = new Data(0, 0);
data.a = jsonObject.getInt("a");
data.b = jsonObject.getInt("b");
return data;
}
public static class Data {
int a;
int b;
public Data(int a, int b) {
this.a = a;
this.b = b;
}
}
Here you can get more info:在这里您可以获得更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.