I am able to convert the complex Java objects like List, ArrayList etc containing huge volume of data into Json efficiently using the Gson library as below code
List<CusPojo> list=new ArrayList<CusPojo>();
.
.
Gson gson=new Gson();
String json=gson.toJson(list);
But if if try the same for a String literal or a String Obj, the conversion is not happening
String msg="success";
**or**
String msg=new String("success");
Gson gson=new Gson();
String json=gson.toJson(msg);
System.out.println("json data-- "+json);
Here i expect the data in Json format like
json data-- {"msg":"success"}
but instead success is what i am getting
json data-- "success"
I couldn't find any explanation regarding this particulary Please help , thank you in advance..
6 Answers 6
Please note, I rarely write java anymore, and I don't have a compiler in front of me, so there could be some obvious bugs here. But try this.
Assuming you have a class for example:
public class Test {
public String msg;
}
You can use it, rather than a string in your gson example.
public static void main(String args[]) {
Test test = new Test();
test.msg = "success"
Gson gson = new Gson();
String json = gson.toJson(test);
}
Comments
For simple cases where you don't want to use a POJO or map you can just create a JsonObject where it's behaviour is close to a map so you can pass the string as value and provide a property name where the JsonObject's toString() will be in JSON format. So you could do the following:
JsonObject jObj = new JsonObject();
jObj.addProperty("msg", msg);
System.out.println(jObj);
Comments
GSon doesn't save you variable name, it saves field name of serialized class
public class StringSerialize{
private String msg;
......
}
Comments
I think you are doing it wrong. your variable msg is just holding the data. try this, let me know if it helps
Map<String,String> map = new HashMap<>();
map.put("msg", "success");
Gson gson = new GsonBuilder().serializeNulls().create();
String json = gson.toJson(map);
System.out.println(json);
Comments
Map<String, String> m = new HashMap<String, String>();
m.put("msg", "success");
Gson gson = new GsonBuilder().create();
System.out.println(gson.toJson(m));
Result
{"msg":"success"}
Comments
Try this for your example:
At first create a model class
class Model {
public String msg;
}
The name of your member is the key in your json
public static void main() {
Model model = new Model();
model.msg = "success"
Gson gson = new Gson();
String json = gson.toJson(test); // Model to json
Model result = gson.fromJson("{\"msg\":\"success\"}", Model.class) // json to Model
}
This is a very good gson-tutorial linked by the gson repository on github
msg + msg?