简体   繁体   English

在没有jackson或gson的情况下将byte []转换为json,反之亦然

[英]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.如果真的那么容易,那么JacksonGson就永远不会出生了。

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.

相关问题 Jackson \\ GSON-Pojo转换为JSON,反之亦然。 文件\\序列化是强制性的吗? - Jackson \ GSON - Pojo to JSON and vice versa. is file \ serialization mandatory? 使用Jackson API和JAXB Annotations将JSON转换为XML,反之亦然 - Converting JSON to XML and vice versa using Jackson API and JAXB Annotations 将字节数组放入 JSON,反之亦然 - Put byte array to JSON and vice versa 将对象(包括lambda)转换为JSON,反之亦然 - Converting object (inclusive lambda) to JSON and vice versa ArrayList转换为Byte,反之亦然 - ArrayList to Byte and vice versa 字节到字符串,反之亦然 - byte to string and vice versa 从xml转换时是否可以维持JSON中的顺序,反之亦然 - Is it possible to maintain ordering in JSON while converting it from xml and vice versa 将深层嵌套的json转换为java对象,反之亦然 - Converting deeply nested json to java object and vice versa 从 Instant 转换为 XMLGregorianCalendar,反之亦然,而不会丢失精度 - Converting from Instant to XMLGregorianCalendar and vice-versa without losing precision 将图像转换为JSON时发生错误(数据损坏),反之亦然 - Error(Data Corruption) occur while converting image into JSON and vice Versa
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM