Handle multiple json response in java - java

I am consuming a Rest API and I am getting multiple Json structure as the API response for different-different use cases.
so, below are the 3 Json format structure.
1.
{
"error":"ash",
"error_description" : "gupta",
"id":"123"
}
2.
"service_response":[
{
"message":"column",
"errorCode":"Invalid_code"
}
]
3. {
"id":"ash",
"success" : "gupta",
"errors":[]
}
I am not able to write the code for different - different Json structure. I am getting parsing exception because I have handled one response. but the problem is how can we identify that which response structure we have to parse.

Related

How to fetch sub json from request parameter

I just decided to send below json data from client to server. Then i found all my previous request were not of type json. And i am unable to send json. Below is the json i want to send in data of jquery ajax.
data:{
id:"10",
sampleArr:[
{ id:"hello","sample":"hello"},
{ id:"hello1","sample":"hello1"}
]
}
and at server i get below parameters
id=10
group[0][id]=hello
group[0][sample]=hello
group[1][id]=hello1
group[1][sample]=hello1
so i am confused how to fetch all groups
One problem is that what you are sending is not valid JSON.
{ "data" : {
"id" : "10",
"sampleArr": [
{ "id" : "hello", "sample" : "hello"},
{ "id" : "hello1", "sample" : "hello1"}
]
}
}
Notice that all attribute names must be quoted, and the top-level JSON object must have curly brackets around it.
If that doesn't help, you need to explain how your servlet is receiving and parsing the JSON.
#BigMike, Thanks i am able to fetch complete json and play around with it. Was unable to send JSON even setting content type application/json. But Still checking why, but working as temperary fix (Might be that i am not using Rest API)

Getting the response from a json response to Google Maps API in Java

I need to develop a program where I have to calculate driving distance and time. Getting the request to the Google Maps API works, and I get a really big response. Now I want to extract the data I need from this response. The response is in json, and the program I make is made in Java. I have no idea to do this. I tried to just put the whole response in a string, and then search the data I need, like "distance" and extract a few characters that come after that. Problem with this is, if something changes in front of it, it's all going to be at different indexes in the huge string.
A response is like this (only a bit of the big thing)
"copyrights" : "Kaartgegevens ©2017 GeoBasis-DE/BKG (©2009), Google",
"legs" : [
{
"distance" : {
"text" : "229 km",
"value" : 229411
},
"duration" : {
"text" : "2 uur 20 min.",
"value" : 8417
},
How do I easily extract the value of both "distance" and "duration"?
Basically what you want to do is serializing and deserializing the JSON to a proper Java object. You can do this by using Frameworks like Jackson or GSON to convert the JSON-String to POJOs.
This might help you as well:
How to serialize and deserialize a JSON object from Google geocode using Java
Converting JSON to Java
http://thegeekyland.blogspot.de/2015/11/serializing-and-deserializing-json-from.html
And I'm pretty sure Google has it's own API that maps the JSON internally, although I haven't used it yet. Here you might find more information:
https://developers.google.com/maps/web-services/?hl=de
Hope this helps!

Accessing JSON array elements in java

I have a json file and have used simple.json jar to parse the elements. I could parse the elements successfully. But what I want is that if my json file has three elements by same name, then I want to print each name only when their index is called.
get() prints out all the elements of that name.
Please help!
Following is the json file:
{
"nodes":
[
{
"node":"1",
"ipaddr":"127.0.0.1",
"port":"8443",
"mgport":"9000"
},
{
"node":"2",
"ipaddr":"127.0.0.1",
"port":"8556",
"mgport":"9000"
},
{
"node":"3",
"ipaddr":"127.0.0.1",
"port":"8000",
"mgport":"9000"
}
]
}
I need to retrive only one port value rather than all the values.
I have successfully used the JSON Processing library to do something similar to what you describe.
Here is the link for you to have a look: https://jsonp.java.net/
Could you post also an example of the JSON you'll like to parse?
Use Jackson for parsing JSON. It will make your life easier.
This will help you.
http://www.tutorialspoint.com/jackson/jackson_first_application.htm
Thanks

How to append object to a json file with JSR 353 (Java API for JSON Processing)

Using JSR-353 (https://jsonp.java.net/index.html)
I would like to open a json file and append some object in the root array, eg :
[{"foo":"bar"}]
I would like with a code about like this :
try(JsonGenerator writer = Json.createGenerator(new FileOutputStream(this.file))){
writer.writeStartObject().write("hello", "world").writeEnd();
} catch (IOException e) {
e.printStackTrace();
}
And obtain in the end :
[
{"foo":"bar"},
{"hello":"world"}
]
Note : I don't want to have to load the full json in-memory to append my data.
Note : I don't want to have to load the full json in-memory to append
my data.
Basically, you can't. You would have to parse the full data structure, so that your write(..) would know where to write. Otherwise, it's just appending somewhere and that might break the JSON format.
So read the JSON from the file, generate a JsonArray from it. Create a new JsonObject from your values. Add it to the array. Then write the full array.
You can't simply "append". In the general case you must read in the JSON, modify the tree-structured memory image, then "serialize" it back to linear JSON.
In very simple cases such as the above you could in theory seek to the end, backspace over the closing ], then write out ,, the second object, and a new closing ], but it's not a general solution to updating JSON.

GSON Can I convert only part of JSON, the ones I want Using GSON.fromJSON()

I am working with a big JSON object which has responses form multiple requests.
And the part I am working on requires only few object and they are not always in front.
For Example the json structure is:
**
json = {
mainDocument: {
element1: {
element11: "value11",
element12: {
element121: "value121"
}
},
element2: {
element21: {
element211: {
element2111: "value2111",
element2112: {
element21121: "value21121"
}
}
},
element22: "value22"
}
}
}
**
This structure can change depending on whether or not the request is successful.
Now,
I want to create an java object with the value of element11, element 22, element21121.
Currently I just check the json and use the setters of the object.
I want to know if there is a way to let GSON handle this and not have to parse the json myself.
Thanks in advance for any help you can offer.
I don't know if I understand your question very well, but in order to deserialize a JSON response with Gson, the most proper way in my opinion is to create a class structure that encapsulates the data in the response. In your case something like:
class Response
MainDocument mainDocument
class MainDocument
Element element1
Element element2
class Element
...
If you only need some data from the JSON, you can omit attributes in your class structure and Gson will ignore them. And if an object can have different contents in different responses, you can have something like this:
class Response
MainDocument mainDocument
Error error
And Gson will parse responses both with a root element mainDocument (like the one in the question) or with a root element error... this allows you to adapt your parsing to variable responses...
Obviously, to follow this approach, you need to know all the possible response structures you can have. If your problem is that your JSON response is absolutely variable, and you cannot create a class struture to wrap it, you always could do a manual parsing, somehting like this:
JsonParser parser = new JsonParser();
JsonObject rootObj = parser.parse(jsonString).getAsJsonObject();
String element21121 = rootObj
.getAsJsonObject("mainDocument")
.getAsJsonObject("element2")
.getAsJsonObject("element21")
.getAsJsonObject("element211")
.getAsJsonObject("element2112")
.getAsString("element21121");

Categories