如何将Java对象转换为JSON字符串? [英] How to convert Java Object to JSON string?
问题描述
您好,我正在尝试将Java对象转换为Json字符串,以便在我的视图中使用javascript函数.
Hello i'm trying to convert my Java Object to a Json string to use in my view with javascript functions.
我尝试使用Google的gson lib:
I tried to use Google's gson lib:
String myjson = "";
Gson gson = new Gson();
myjson = gson.toJson(myuser);//myuser is my java object
但是,当我调用myjson时,它由""
"而不是字符""
"组成,因此我无法在我的视图中使用它,这给我带来了麻烦.
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.
如何解决此问题,如何正确创建Json字符串?
How can I fix this, how can I create Json string properly?
渲染myjson时是否有可能犯错误?
Edit : Is there a chance of making a mistake while rendering the myjson?
Edit2:要在视图中达到myjson的结果,我正在做
To reach the result of myjson in view, i'm doing
render(myjson);
render(myjson);
在我的代码末尾.
Edit3:Play框架具有renderJSON()方法.但是我不能使用它,因为我不仅在渲染myjson和其他元素.
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.
推荐答案
请注意,&"是正确的" JSON,因此无论您是否不想在JSON中使用实体,JavaScript都可以正确地转义.您要禁用html格式/转义.
Note that """ 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.
尝试使用
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
检查GSONBuilder对象文档 http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/GsonBuilder.html
Check the GSONBuilder Object Documentation http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/GsonBuilder.html
这篇关于如何将Java对象转换为JSON字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!