简体   繁体   中英

How to extract JSON String data?

I have JSON string which is in a standalone Java project:

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

I want to extract MsgType from this which is AB

Which is the best way to do it?

You can use Gson library for this.

            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

{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:

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):

/*
{"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 :

JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(yourString);
String msgType = (String) jsonObject.get("MsgType");

Check this link for a complete example.

JsonPath

For parsing simple JSON use JsonPath

JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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