简体   繁体   中英

Convert complete object to JSON

Hi I have a class like this :

public class A {
String x;
String y;
String data;
}

The variables x and y contain normal Strings but variable data contains a JSON string, ie, '

x = "aaaa";
y = "bbbb";
data = "{\"key\":\"val\"}";

I want to convert the complete object in JSON such that final output is :

{
x : "aaaa",
y : "bbbb",
data : {
      "key" : "val"
       }
}

I tried using new JSONObject(object) to convert the object to JSON. It does fine for x and y attributes but the data remains as a String like this :

data : "{\\\"key\\\":\\\"value\\\"}"

. I want data to be JSONified as well in one go.

How to implement this?

The simplest way is having your data field be another object.

public class Data {

   String key;
   String val;
}

and in your class;

public class A { //Java classes start with uppercase

   String x;
   String y;
   Data data;
}

If you don't want to modify the class or create new class extending from it, You can just remove unnecessary characters:

public class Main {

  public static void main(String[] args) {

    a obj = new a();
    obj.x = "aaaa";
    obj.y = "bbbb";
    obj.data = "{\"key\":\"val\"}";

    String str = new JSONObject(obj).toString().replaceAll("\\\\", "")
            .replaceAll("\"\\{", "{")
            .replaceAll("\\}\"", "}");
    System.out.println(str);
  }
}

output:

{"data":{"key":"val"},"x":"aaaa","y":"bbbb"}

or you can use org.apache.commons.text.StringEscapeUtils.unescapeJson to do the work easily.

Given OP response to Doga Oruc answer here is a workaround: Read your String from member Data and parse that JSON string to Map<String, Object> using JsonObject class. Then parse your class A to JSON and parse it back to Map<String, Object> . In that second map replace key "data" with the value of your first map. This is obviously cumbersome, but that's the price for not being able to modify your original class

How about something like this with Jackson?

    class AWrapper {
        String x;
        String y;
        Object data;

        public AWrapper(A a, ObjectMapper mapper) throws IOException {
            this.x = a.x;
            this.y = a.y;
            this.data = mapper.readValue(a.data, Object.class);
        }

        public String getX() {
            return x;
        }
        public String getY() {
            return y;
        }
        public Object getData() {
            return data;
        }
    }

    class SomeClass {
        public static String toJson(A a) throws IOException {
            ObjectMapper mapper = new ObjectMapper();
            AWrapper aWrapper = new AWrapper(a, mapper);
            return mapper.writeValueAsString(aWrapper);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM