英文:
Converting byte[] to json and vice versa without jackson or gson
问题
我有一个使用Java 1.5构建的遗留应用程序,我需要在字节数组(byte[])和JSON之间进行转换,但我不能使用jackson或gson,因为它们适用于更高版本的java。
我有如下的方法,但我无法找到使用JSONObject实现的方法:
public <T> T toObj(byte[] bytes, Class<T> responseType) {
}
英文:
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.
I have methods like these and I couldn't find a way to implement with JSONObject :
public <T> T toObj(byte[] bytes, Class<T> responseType) {
}
答案1
得分: 2
如果事情真的那么简单,那么 Jackson
或者 Gson
就不会诞生。
恐怕您必须为所有对象手动声明反序列化器。这不是火箭科学,但是需要花时间来完成。这是一个示例:
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;
}
}
这里您可以获取更多信息:
英文:
If it would be so easy, then Jackson
or Gson
was never be born.
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:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论