How to convert Java Object to JSON string?

2019-08-02 09:51发布

Hello i'm trying to convert my Java Object to a Json string to use in my view with javascript functions.

I tried to use Google's gson lib:

String myjson = "";
Gson gson = new Gson();
myjson = gson.toJson(myuser);//myuser is my java object

However when i call myjson, it consists of '"' instead of the character '"' for this reason i can't able to use it in my view, it is creating me problems.

How can I fix this, how can I create Json string properly?

Edit : Is there a chance of making a mistake while rendering the myjson?

Edit2: To reach the result of myjson in view, i'm doing

render(myjson);

at the end of my code.

Edit3: Play framework has a method of renderJSON(). However i can't use it since i'm rendering not only myjson and some other elements too.

2条回答
\"骚年 ilove
2楼-- · 2019-08-02 10:11

Note that "&quot" is "Proper" JSON, so your javascript can be escaped properly, anyways if you dont want to use entities in you JSON perhaps you want to disable html formatting/escaping.

Try using

Gson gson = new GsonBuilder().disableHtmlEscaping().create();

Check the GSONBuilder Object Documentation http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/GsonBuilder.html

查看更多
对你真心纯属浪费
3楼-- · 2019-08-02 10:17

I think he's protecting you against html special chars.

Try something like that:

Gson gson = new Gson();
String target = "my text";
String json = gson.toJson(target);

This code is extract from http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html (the api).

查看更多
登录 后发表回答