简体   繁体   English

如何提取JSON字符串数据?

[英]How to extract JSON String data?

I have JSON string which is in a standalone Java project: 我有一个独立的Java项目中的JSON字符串:

{"MsgType":"AB","TID":"1","ItemID":"34532136","TransactTime":1389260033223}

I want to extract MsgType from this which is AB 我想从这个AB提取MsgType

Which is the best way to do it? 这是最好的方法吗?

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将包含这样的keyvalues映射

{MsgType=AB, TID=1.0, ItemID=3.4532136E7, TransactTime=1.389260033223E12}

I use JSONObject under android but from Oracle docs I see its also available under javax.json package: 我在android下使用JSONObject但是从Oracle docs我看到它也可以在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);

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 link for a complete example. 请查看此链接以获取完整示例。

JsonPath 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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM