-2
{
    "city" : "THAYNE",
    "loc" : [
            -111.011354,
            42.933026
    ],
    "pop" : 505,
    "state" : "WY",
    "_id" : "83127"
}

I have this json syntax, and I would like to parse it to a Java object. First of all, I made a String array, to save every line of .json file. But after all I don't really know, what should I do.

Bucket
  • 7,415
  • 9
  • 35
  • 45
chabeee
  • 305
  • 3
  • 14
  • 1
    There are like a zillion tools for this outside, what's the matter wich searching and trying instead of posting basic questions on SO? – Smutje Mar 05 '14 at 20:05

3 Answers3

3
###Gson is easy to learn and implement, what we need to know are following two methods

toJson() – Convert Java object to JSON format
fromJson() – Convert JSON into Java object ###

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;

public class GsonExample {
    public static void main(String[] args) {

    Gson gson = new Gson();

    try {

        BufferedReader br = new BufferedReader(
            new FileReader("c:\\file.json"));

        //convert the json string back to object
        DataObject obj = gson.fromJson(br, DataObject.class);

        System.out.println(obj);

    } catch (IOException e) {
        e.printStackTrace();
    }

    }
}
venkat
  • 449
  • 4
  • 17
0

I will get creamed for advising to use a library, but use Gson: https://code.google.com/p/google-gson/

Create a JsonParser object and go from there. Easiest by far. Also, you don't need the input in a stringarray, create one String with the entire JSON in it. Try this:

JsonParser parser = new JsonParser();
try
{
    JsonElement json = parser.parse("your json string");
    JsonObject obj = json.getAsJsonObject();
    // Now you have the JSon object, get any element from it now. 
    JsonElement city = obj.get("city");
    return city.getAsString();
} 
catch ( JsonSyntaxException e ) {
}
catch ( JsonParseException e ) {
}
mvreijn
  • 2,807
  • 28
  • 40
0

You can use GSON - A Java library that can be used to convert Java Objects into their JSON representation and vice-versa

Ankur Aggarwal
  • 2,993
  • 5
  • 30
  • 56