2

I have checked out many pages but most of the tutorials and script return an error code with this type of JSON output. So how would I be able to extract the data from this JSON in Java?:

[
  {
    "user":{"id":"1","username":"user1"},
    "item_name":"item1",
    "custom_field":"custom1"
  },
  {
    "user":{"id":"2","username":"user2"},
    "item_name":"item2",
    "custom_field":"custom2"
  },
  {
    "user":{"id":"3","username":"user3"},
    "item_name":"item3",
    "custom_field":"custom3"
  }
]
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Aronnn
  • 63
  • 1
  • 6
  • Have you already downloaded the data from the URL and want to know how to read it? Or do you want to know how to download it in the first place? – ArjunShankar Apr 03 '12 at 13:50
  • 1
    Possible duplicate: http://stackoverflow.com/questions/1688099/converting-json-to-java/1688182#1688182 – Ryan Elkins Apr 03 '12 at 13:53
  • Many libs want the entire JSON content to be wrapped in { } so you an try to wrap your JSON data in curly braces. I usualy use json-lib to read it `JSONObject.fromObject( yourJsonString );` – luukes Apr 03 '12 at 13:56
  • @luukes, not true, you can have a `JSONArray` created too. It doesn't necessarily mean that you always have to create a `JSONObject` wrapper for `JSONArray`. – Buhake Sindi Apr 03 '12 at 14:00
  • I have not downloaded the json, but I already have a working script to get the json to a string. I only need the conversion to get it in java. – Aronnn Apr 03 '12 at 14:04
  • @Aronnn - if you only want to convert from string to Java, look at the answer linked by Ryan Elkins in an earlier comment. – ArjunShankar Apr 03 '12 at 14:07
  • @ArjunShankar, I can not figure out how to use Google GSON to convert it to a Java variable. I have tried it a few different times now but cannot seem to get it working, how would I be able to do this? – Aronnn Apr 03 '12 at 14:39
  • @Aronnn - I've tried to answer that below. – ArjunShankar Apr 03 '12 at 14:52

3 Answers3

1

If you want to use Gson, then first you declare classes for holding each element and sub elements:

public class MyUser {
  public String id;
  public String username;
}

public class MyElement {
  public MyUser user;
  public String item_name;
  public String custom_field;
}

Then you declare an array of the outermost element (because in your case the JSON object is a JSON array), and assign it:

MyElement[] data = gson.fromJson (myJSONString, MyElement[].class);

Then you simply access the elements of data.

The important thing to remember is that the names and types of the attributes you declare should match the ones in the JSON string. e.g. "id", "item_name" etc.

ArjunShankar
  • 23,020
  • 5
  • 61
  • 83
  • I've attempted to use this but it is still getting errors, here is a pastebin link to what I have: http://pastebin.com/nRiGqq9r If I use 'MyElement[] data = new Gson().fromJson(jsonText, MyElement.class);' it will tell me I need to change MyElement[] to MyElement, so this also doesn't work, how will I be able to make this script work? – Aronnn Apr 03 '12 at 18:23
  • @Aronnn - In your fromJson call, the type you are assigning to is supposed to be `MyElement[].class`, not `MyElement.class` – ArjunShankar Apr 04 '12 at 08:23
  • Here is my script with the error I am getting, I really can't seem to figure out what the problem is: http://pastebin.com/iR7ysMx6 – Aronnn Apr 04 '12 at 11:31
  • You have multiple problems. The JSON you are reading is BAD. There is a `.` instead of a `,` somewhere. See carefully. Secondly, you cannot declare `MyElement` and `MyUser` as nested classes. How will Gson be able to access the constructors for those classes if it cannot see them? – ArjunShankar Apr 04 '12 at 12:54
  • When finding problems, and requesting help, I suggest you consider making an example that complies with http://sscce.org ; For example, if you had separated downloading the JSON from parsing the JSON, and used a short, correct, hardcoded string instead, you would have seen yourself that the HTTP URL produces bad JSON. – ArjunShankar Apr 04 '12 at 12:57
  • I am sorry I am asking so many questions, I fixed the part you told me to and once I attempt to output it it will return something like: `com.aronnn.fwdonate.MyElement@4413ee`, how will I be able to output for example the item_name from user2? – Aronnn Apr 04 '12 at 13:36
  • @Aronnn - how familiar are you with Java? `data` is meant to be accessed, not printed. e.g. `data[1].item_name` contains the item name of the 2nd element of `data` array. `data[0].user.id` contains the user Id of the 1st element of the `data` array. – ArjunShankar Apr 04 '12 at 13:40
  • Some features are still kind of new to me and I guess this was not the best way to start with it. But thank you very much, everything works fine now! So thanks for all the help! – Aronnn Apr 04 '12 at 13:48
  • Welcome! Practice makes perfect. – ArjunShankar Apr 04 '12 at 13:48
0

You could try JSON Simple
http://code.google.com/p/json-simple/

Example:

JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(jsonDataString);

for (int i = 0; i < jsonArray.size(); i++) {
    JSONObject obj = (JSONObject) jsonArray.get(i);
    //Access data with obj.get("item_name")
}

Just be careful to check for nulls/be careful with casting and such.

Nick DeFazio
  • 2,412
  • 27
  • 31
0

If your trying to serialize/deserialize json in Java I would recommend using Jackson. http://jackson.codehaus.org/

Once you have Jackson downloaded you can deserialize the json strings to an object which matches the objects in JSON.

Jackson provides annotations that can be attached to your class which make deserialization pretty simple.

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189