如何在 Java 中读取字符串化的 JSON 字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4437213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read stringified JSON string in Java
提问by Callie
Kindly need your help as this really taking me long time to try. From JSP, I passed the stingnify JSON object as a String to the Java action, it like
请需要您的帮助,因为这真的需要我很长时间才能尝试。从 JSP,我将 stingnify JSON 对象作为字符串传递给 Java 操作,就像
String jsonDealer = [{"dealerID":"VARSSWK103","dealerName":"NPD STATION SDN BHD"},
{"dealerID":"VARSSTH008","dealerName":"Winjaya Teleshop"}]
How I can convert this to JSON object/ or ArrayList of Dealer, so that I can retrieve the dealer ID and dealer name?
如何将其转换为经销商的 JSON 对象/或 ArrayList,以便我可以检索经销商 ID 和经销商名称?
Thanks for all help!!!
谢谢大家的帮助!!!
回答by Richard H
Well you could write your own JSON parser, but there's no need to re-invent the wheel - there are a number of robust, mature JSON parsers freely available. I use JSONObjectand JSONArrayfrom Tapestry. If you downloadTapestry 5 and unpack it, then just include the library tapestry-core-5.0.18.jar
in your build path and you'll be set to go. Both JSONObject and JSONArray take a String as constructor argument, and the api is fully documented in those links.
好吧,您可以编写自己的 JSON 解析器,但无需重新发明轮子 - 有许多免费提供的强大、成熟的 JSON 解析器。我使用 Tapestry 的JSONObject和JSONArray。如果您下载Tapestry 5 并解压缩它,那么只需将库包含tapestry-core-5.0.18.jar
在您的构建路径中,您就可以开始使用了。JSONObject 和 JSONArray 都采用 String 作为构造函数参数,并且这些链接中完整记录了 api。
回答by bbcooper
using http://json-lib.sourceforge.net/can be realy easy.
使用http://json-lib.sourceforge.net/真的很容易。
See http://json-lib.sourceforge.net/snippets.html
见http://json-lib.sourceforge.net/snippets.html
String str = "{'dealerName':'NPD STATION SDN BHD', 'dealerID': 1, 'dealerReputation': 2.0, 'dealerActive': true}";
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( str );
and
和
String str = "['NPD STATION SDN BHD', 1, 2.0, true]";
JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( str );