How to extract JSON String data? How to extract JSON String data? json json

How to extract JSON String data?


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.