I have a java class Object:
class TempClass {
@Expose
String errorCode
@Expose
String message
String name
String cause
TempClass(String errorCode, String message) {
this.errorCode = errorCode
this.message = message
}
}
I am able to convert object into json using GSON jar
TempClass t = new TempClass("404","page not found")
GsonBuilder builder = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
String json = builder.create().toJson(t);
The JSON String I am getting is
{ errorCode: "404", message: "page not found" }
But What I want is:
"TempClass"{ errorCode: "404", message: "page not found" }
Or Better if there is any other sophisticated way where I can map "tempClass" (or any other property) into something else.
You can try creating a Map, where "tempClass" is the key and your TempClass object is the value, like this:
TempClass t = new TempClass("404","page not found")
Map<String, Object> map = new Hashmap<String, Object> ();
map.put("tempClass", t);
GsonBuilder builder = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
String json = builder.create().toJson(map);
This is a sort of easy and fast way to achieve what you need due to Maps are parsed out-of-the-box by Gson, but be careful: in case you have more properties like this one, it could be better to create a new class for that
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.