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

Dungeon Hunter
  • 19,827
  • 13
  • 59
  • 82
user1321824
  • 445
  • 3
  • 22
  • 41

2 Answers2

1

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

Here's an example: Converting JSON to Java

Community
  • 1
  • 1
Luca Matteis
  • 29,161
  • 19
  • 114
  • 169
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.

Nishant
  • 54,584
  • 13
  • 112
  • 127