Reputation: 1
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, i.e, '
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?
Upvotes: 0
Views: 278
Reputation: 431
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);
}
}
Upvotes: 0
Reputation: 1275
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.
Upvotes: 0
Reputation: 7808
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
Upvotes: 0
Reputation: 826
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;
}
Upvotes: 5