Java 如何提取JSON字符串数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21016780/
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 extract JSON String data?
提问by Swarne27
I have JSON string which is in a standalone Java project:
我有一个 JSON 字符串,它在一个独立的 Java 项目中:
{"MsgType":"AB","TID":"1","ItemID":"34532136","TransactTime":1389260033223}
I want to extract MsgType
from this which is AB
我想提取MsgType
从这个是AB
Which is the best way to do it?
哪种方法最好?
采纳答案by Sinto
You can use Gson library for this.
您可以为此使用 Gson 库。
String json="{MsgType:AB,TID:1,ItemID:34532136,TransactTime:1389260033223}";
Map jsonJavaRootObject = new Gson().fromJson(json, Map.class);
System.out.println(jsonJavaRootObject.get("MsgType"));
where the jsonJavaRootObject will contain a map of keyvalues like this
其中 jsonJavaRootObject 将包含这样的键值映射
{MsgType=AB, TID=1.0, ItemID=3.4532136E7, TransactTime=1.389260033223E12}
回答by MariuszS
JsonPath
路径
For parsing simple JSON use JsonPath
解析简单的 JSON 使用JsonPath
JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document.
JsonPath 之于 JSON 就像 XPATH 之于 XML,这是一种提取给定文档部分的简单方法。
Example code
示例代码
String json = "{\"MsgType\":\"AB\",\"TID\":\"1\",\"ItemID\":\"34532136\",\"TransactTime\":1389260033223}";
String author = JsonPath.read(json, "$.MsgType");
System.out.println(author);
Result
结果
AB
Dependency
依赖
'com.jayway.jsonpath:json-path:0.9.1'
回答by Sergi
I have an example with json-simple:
我有一个json-simple的例子:
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(yourString);
String msgType = (String) jsonObject.get("MsgType");
Check this linkfor a complete example.
检查此链接以获取完整示例。
回答by marcinj
I use JSONObject under android but from Oracle docs I see its also available under javax.json package:
我在 android 下使用 JSONObject 但从 Oracle 文档中我看到它在 javax.json 包下也可用:
http://docs.oracle.com/javaee/7/api/javax/json/package-summary.html
http://docs.oracle.com/javaee/7/api/javax/json/package-summary.html
If you want Gson then your code should look like below (sorry not compiled/tested):
如果你想要 Gson,那么你的代码应该如下所示(抱歉没有编译/测试):
/*
{"MsgType":"AB","TID":"1","ItemID":"34532136","TransactTime":1389260033223}
*/
Gson gson = new Gson();
static class Data{
String MsgType;
String TID;
String ItemID;
int TransactTime;
}
Data data = gson.fromJson(yourJsonString, Data.class);