2

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?

3
  • 1
    have you tried anything using gson? Commented Jan 9, 2014 at 9:54
  • can it be done with gson Commented Jan 9, 2014 at 9:55
  • @Swarnajith yes it can be done with Gson, I posted one way of doing it Commented Jan 9, 2014 at 10:10

4 Answers 4

5

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}
Sign up to request clarification or add additional context in comments.

1 Comment

@Swarnajith please mark it as answer if you found it useful, so that it will help other people also.
3

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

1 Comment

+1...deserialize json data into model class is a much better way.
2

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.

1 Comment

I forgot the JSONParser. Thanks @Suvonkar.
1

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.