GSON parsing without a lot of classes - java

I have the following JSON and I'm only interested in getting the elements "status", "lat" and "lng".
Using Gson, is it possible to parse this JSON to get those values without creating the whole classes structure representing the JSON content?
JSON:
{
"result": {
"geometry": {
"location": {
"lat": 45.80355369999999,
"lng": 15.9363229
}
}
},
"status": "OK"
}

You don't need to define any new classes, you can simply use the JSON objects that come with the Gson library. Heres a simple example:
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(json).getAsJsonObject();
JsonObject locObj = rootObj.getAsJsonObject("result")
.getAsJsonObject("geometry").getAsJsonObject("location");
String status = rootObj.get("status").getAsString();
String lat = locObj.get("lat").getAsString();
String lng = locObj.get("lng").getAsString();
System.out.printf("Status: %s, Latitude: %s, Longitude: %s\n", status,
lat, lng);
Plain and simple. If you find yourself repeating the same code over and over, then you can create classes to simplify the mapping and eliminate repetition.

It is indeed possible, but you have to create a custom deserializer. See Gson documentation here and Gson API Javadoc here for further info. And also take a look at other reponses of mine here and here... and if you still have doubts, comment.
That said, in my opinion it is much easier for you to parse it creating the correspondent classes, even more taking into account the simplicity of your JSON response... With the usual approach you only have to write some super-simple classes, however, writing a custom deserializer, although is not that complex, it will take you probably longer, and it will be more difficult to adapt if later on you need some data else of your JSON...
Gson has a way of operating that has been designed for developers to use it, not for trying to find workarounds!
Anyway, why do you not want to use classes? If you don't like to have many classes in your project, you can just use nested classes and your project will look cleaner...

Related

Treves the JSON object and manipulate the value in java

What im trying to do is
JSON:
{
aKey:{
aChildKey:""
},
bKey:""
}
expected:
aKey:{
aChildKey:"aKey.aChildKey"
},
bKey:"bKey"
}
Please can some one help me in getting the expected the value
You need to deserialize the JSON into an object, set the values, then serialize it back into JSON. There are a number of libraries you can use for this, like org.json, gson, or Jackson. Those libraries also allow you to modify the value directly. For example, using org.json, you can do something like this:
JSONObject jsonObject = new JSONObject(myJsonString);
jsonObject.getJSONObject("akey").put("aChildKey","aKey.aChildKey");
See How to parse JSON in Java

Is there a better/easier way to update a json file in Java?

Say, I have a json file like below:
[{
"obj1_key1":"aa",
"obj1_array":[{"e1":"11"},{"e2":"22"}]
},
{
"obj2_key1":"cc",
"obj2_key2":"dd"
}]
Now I want update the file into something like below:
[{
"obj1_key1":"aa",
"obj1_array":[{"e1":"11"},{"e2":"22"},{"e3":"333"}]
},
{
"obj2_key1":"cc",
"obj2_key2":"dd"
}]
I tried using ObjectMapper to parse the file like
JsonNode jsonFile = new ObjectMapper().readTree(new File("file.json");
however then I need to find the obj1_array and append a json object, then write the json object back to the file. And I don't think the way I load the json file as a JsonNode is a easy way because I should convert it between Json/JsonArray back and forth. So I'm wondering is there a simpler way to make this work? Really appreciate that.
if it is just a one-off case, you can use your preferred mechanism, but if it is going to used often, I would prefer
Convert the JSON to a POJO ( using some parser eg Jackson )
Update the requisite fields
Return the Json object.

How to convert String in java to Json

How can i convert such a string to json in java?
String mycode = "{
"name": "Test",
"Status": {
"code": 200,
"request": "get"
}
}";
thanks
Using org.json library:
JSONObject jsonObj = new JSONObject(mycode);
I find Google gson to be extremely convenient and (that's not so frequent) to be very light and not leaving traces in your code except in the point where you make the json production (if you don't need specific conversions).
http://code.google.com/p/google-gson/
GSON is a good open source library that would fit your use case. here is the link - http://code.google.com/p/google-gson/

Create JSON object and convert it to String in Java

I need to send a quite long JSON header through an http post. In Python was like this:
self.body_header = {
"client": self.client_name,
"clientRevision": self.client_version,
"uuid": str(uuid.uuid4()),
"session": self.get_sessionid()}
self.body = {
"header": self.body_header,
"country": {"IPR":"1021", "ID":"223", "CC1":"0", "CC2":"0", "CC3":"0", "CC4":"2147483648"},
"privacy": 1}
I need to do something similar in Java, ie, create somehow a JSON struct, convert it to a String and send it via http.
The question is, how can I achieve that easily? Any useful libraries? I know how to send it, but not how to build it and then create a String.
Thank you all.
You can use gson.
You can create a Java Object (POJO) and serialize it as JSON by doing:
Gson gson = new Gson();
String json = gson.toJson(yourObject);
You can then send the string over HTTP.
If you do not want to go the POJO route, you can still create the JSON struct using JsonElement, JsonArray, JsonObject in the Gson API.
I like the original org.json
i think STO had a similar discussion https://stackoverflow.com/questions/338586/a-better-java-json-library

How do I modify a large json string?

Dead silence! Not often you experience that on Stackoverflow... I've added a small bounty to get things going!
I've built a json document containing information about the location of various countries. I have added some custom keys. This is the beginning of the json-file:
{
"type": "FeatureCollection",
"features": [
{ "type": "Feature", "properties": {
"NAME": "Antigua and Barbuda",
"banned/censored": "AG",
"Bombed": 29,
"LON": -61.783000, "LAT": 17.078000 },
"geometry": { "type": "MultiPolygon", "coordinates": [ [ [ [ -61.686668,...
All the custom keys (like bombed, banned/censored etc.) have values, but they are just old (bogus if you want) values. The real values are kept in a .csv file extracted from a excel document.
I e.g. have this:
banned/censored bombed
Antigua and Barbuda 2 120
...
Now I want to match these values with the proper key in the json-file. Is there any programs out there that I can use? Another option would be a json library for java, which somehow supports what I want. I havent been able to find an easy solution for it yet. The document is pretty large ~ 10MB, if it makes any difference!
EDIT: I've used QGIS to manipulate the .shp file, so some kind of extension could be of use too.
Just convert both the JSON and the CSV to a fullworthy Java object. This way you can write any Java logic to your taste to alter the Java objects depending on the one or other. Finally convert the modified Java object representing the JSON data back to a JSON string.
There is however one problem in your JSON. The / in banned/censored is not a valid character for a JSON field name, so many of the existing JSON deserializers may choke on this. If you fix this, then you'll be able to use one of them.
I can recommend using Google Gson for the converting between JSON and Java. Here's a kickoff example based on your JSON structure (with banned/censored renamed to bannedOrCensored):
class Data {
private String type;
private List<Feature> features;
}
class Feature {
private String type;
private Properties properties;
private Geometry geometry;
}
class Properties {
private String NAME;
private String bannedOrCensored;
private Integer Bombed;
private Double LON;
private Double LAT;
}
class Geometry {
private String type;
private Double[][][][] coordinates;
}
You only need to add/generate getters and setters yourself. Then, you'll be able to convert between JSON and Java like follows:
Data data = new Gson().fromJson(jsonString, Data.class);
To convert between CSV and a Java object, just pick one of the many CSV parsers, like OpenCSV. You can even homegrow your own with help of BufferedReader.
Finally, after altering the Java object representing the JSON data, you can convert it back to JSON string with help of Gson as follows:
String json = new Gson().toJson(data);
While BalusC's answer tells you how to do it in your current setup, I have a more radical suggestion: get rid of the JSON.
By idea JSON is not meant to store data - it is meant to be used as a "lightweight text-based open standard designed for human-readable data interchange". That is:
low-traffic (as little non-meaningful data as possible)
human-readable
easy to handle with dynamic languages
Data storages on the other hand have much more requirements than this. That's why databases exist. So move your storage to a database. If you don't want a full-featured database, use something like HSQLDB or JavaDB.

Categories