Question

I am trying to parse some JSON data to Java using GSON but I am unable to do so due to the way it is formatted. I've looked around a lot but none of the information I found helped me work this out. I haven't had much experience with JSON, especially when parsing it to Java. I would appreciate any help I get for this.

JSON URL: http://xpaw.ru/mcstatus/status.json

EDIT:

I took your advise about using Jackson and went through some guides and tried making it, Heres my code:

Main Class: http://pastebin.com/XRcpkAuP

UptimeCheck Class: pastebin/f2UanvhY (Sorry, I couldnt post more than 2 links :/)

For some reason, It doesnt seem to be able to parse the link. Could someone please help me out? Thank You

Was it helpful?

Solution

I personally recommend to use Jackson to convert JSON to/from Java. Jackson is a High-performance JSON processor Java library.

Below snippets would give a basic idea to this library.

//1. Convert JSON to Java object
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(new File("c:\\report_data.json"), ReportData.class);

//2. Convert Java object to JSON format
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("c:\\report_data.json"), reportData);

Both writeValue() and readValue() has many overloaded methods to support different type of InputStream and OutputStream.

Example for your reference: http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/

Shishir

OTHER TIPS

I dont know about gson, but your JSON String is valid. You can use the following:

This is simple code to do it, I avoided all checks but this is the main idea.

 public String parse(String jsonLine) {
    JsonElement jelement = new JsonParser().parse(jsonLine);
    JsonObject  jobject = jelement.getAsJsonObject();
    jobject = jobject.getAsJsonObject("data");
    JsonArray jarray = jobject.getAsJsonArray("translations");
    jobject = jarray.get(0).getAsJsonObject();
    String result = jobject.get("translatedText").toString();
    return result;
}

To make the use more generic - you will find that the [javadoc][1] of this are pretty clear and helpful.

I read it in another article.. Using GSON seems to be good....

Simplest thing usually is to create matching Object hierarchy, like so:

This is an example

public class Wrapper {
   public Data data;
}
static class Data {
   public Translation[] translations;
}
static class Translation {
   public String translatedText;
}

and then bind using GSON, traverse object hierarchy via fields. Adding getters and setters is pointless for basic data containers.

So something like:

Wrapper value = GSON.fromJSON(jsonString, Wrapper.class);
String text = value.data.translations[0].translatedText;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top