【问题标题】:Converting byte[] to json and vice versa without jackson or gson在没有杰克逊或 gson 的情况下将 byte[] 转换为 json,反之亦然
【发布时间】:2020-12-30 13:27:23
【问题描述】:

我有一个使用 java 1.5 构建的遗留应用程序,我需要在 byte[] 和 json 之间进行转换,但我不能使用 jackson 或 gson,因为它们位于更高版本的 java 中。 我有这样的方法,但我找不到用JSONObject 实现的方法:

public <T> T toObj(byte[] bytes, Class<T> responseType) {
    
}

【问题讨论】:

  • 我有点困惑。你想调用这两个方法对吗?为什么需要在 json 对象中序列化?您只需调用声明 byte[] 的字段来调用/使用这些服务。
  • 实际上我正在尝试为其余服务的基本 http 调用构建一个库,在我的库中我需要这种我无法实现的方法
  • 它是用 Java 1.5 编写的还是仅限于 1.5 版本的 JVM?
  • 是的,它是 java 1.5。我不能使用更高版本的java

标签: java json


【解决方案1】:

如果真的这么简单,那JacksonGson 就永远不会诞生了。

我很害怕,您必须手动为所有对象声明反序列化器。这不是一门火箭科学,但要做到这一点需要时间。这是一个例子:

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;
    }
}

您可以在此处获取更多信息:

【讨论】:

  • 1+,没有 JSONObject 的任何其他解决方案可以利用泛型?
  • 尝试使用旧版本的JackosnGsonjava 5 下工作
猜你喜欢
  • 2017-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-16
  • 1970-01-01
  • 2011-05-18
相关资源
最近更新 更多