0

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) {
    
}
Mostafa
  • 3,002
  • 10
  • 52
  • 79
  • I am a little bit in confusion. you want to invoke these two methods right? Why do you need to serialize in in json object? You just call declare a field of byte[] to call/consume these services. – user404 Sep 12 '20 at 05:35
  • Actually I'm trying to build a library for basic http call to the rest services, in my library i need such method which i couldn't implement – Mostafa Sep 12 '20 at 05:43
  • Has it been written in Java 1.5 or are you limited to a 1.5 version JVM ? – Marged Sep 12 '20 at 05:47
  • Yes, it's java 1.5. I cannot use higher version of java – Mostafa Sep 12 '20 at 05:50

1 Answers1

2

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:

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35