0

Hi I have a json input file as follows,

{'Latitude':'20',
 'coolness':2.0,
 'altitude':39000,
 'pilot':{'firstName':'Buzz',
          'lastName':'Aldrin'},
 'mission':'apollo 11'}

How to create a java object from the json input file.

Thanks

2
  • google has made a library for this: code.google.com/p/google-gson Commented Aug 13, 2012 at 9:03
  • Go to json.org and see the "Java" subsection. Commented Aug 13, 2012 at 9:08

2 Answers 2

1

You can use the very simple GSON library, with the Gson#fromJson() method.

Here's an example: Converting JSON to Java

Sign up to request clarification or add additional context in comments.

2 Comments

If input file may be any JSON file(without particular format),then how to parse it?
ok i m reading opening and reading the file but how to dynamically generate Data class as shown in example(Converting JSON to Java)
1

There are more than one APIs that can be used. The simplest one is JSONObject

Just do the following:

JSONObject o = new JSONObject(jsonString);
int alt = o.getInt("altitude");
....

there are getXXX methods for each type. It basically stores the object as a map. This is a slow API.

You may use Google's Gson, which is an elegant and better library -- slightly more work required than JSONObject. If you are really concerned about speed, use Jackson.

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.