gson.fromJson() method converting invalid json to valid json - java

In my program i am taking input from rest client in json format and retrieving the json from request body i am using gson.fromJson method for retrieving json.
BufferedReader reader = request.getReader();
JsonElement jsonElement = gson.fromJson( reader , JsonElement.class );
Input json, i am passing to rest client :
It is not a valid json.
{
"buildName":FHGF"",
"deadline":"2017-07-28T23:11:15+00:00",
"release":"0.2",
"platformRelease":"5.10.0",
"platformBuild":"1.0.0",
"releatedProducts":"##Product*****",
"expiresInPronto":"2017-07-28T23:11:15+00:00",
"changeNotesRequired":"yes",
"environment":"ah",
"stateTestedInUse":"no"
}
Json which is created by gson :
{
**"buildName":"FHGF\"\""**,
"deadline":"2017-07-28T23:11:15+00:00",
"release":"0.2",
"platformRelease":"5.10.0",
"platformBuild":"1.0.0",
"releatedProducts":"##Product*****",
"expiresInPronto":"2017-07-28T23:11:15+00:00",
"changeNotesRequired":"yes",
"environment":"ah",
"stateTestedInUse":"no"
}
Instead of throwing error gson has converted it to valid json.

Related

SQS - Sending payload with JSONObject push empty objects

I was testing different payload structures accepted by AWS SDK (org.springframework.cloud:spring-cloud-starter-aws-messaging:2.2.6.RELEASE). I am sending the message using convertAndSend function provided by QueueMessagingTemplate. I am able to send it successfully with a string payload or a custom java object. However, when I convert my custom java object to a JSONObject, and push the JSONObject to SQS, it seems the the messageBody being pushed is {empty:true}. When I send it with jsonObject.toString(), it works well though. I am confused on why convertAndSend works for custom java class/object but not for JSONObject type.
Below is a sample code on how I am doing the JSON conversion:
public JSONObject toJson() throws Exception {
JSONObject json = new JSONObject();
json.put("payload", this.payload);
json.put("id", this.taskId);
return json;
}
SQS only allows message content that is JSON formatted string. JSONObject is a Java object. To get it to a JSON formatted string your method needs to look like this:
public String toJson() throws Exception {
JSONObject json = new JSONObject();
json.put("payload", this.payload);
json.put("id", this.taskId);
return json.toString();
}

Extract cloudant document in java

I received response from cloudant and I want parse the response.
My response is,
{"_id":"id_name_list","_rev":"5-9e6b089e3094955395d1c976c5d87392","1":"aa","2":"bb","3":"cc","4":"dd"}
Code to convert response to JSON is,
JSONObject jo = new JSONObject(response);
String s = jo.get("1");
I am getting the error:
org.json.JSONException: JSONObject["1"] not found.

Gson HTTP response object

I am using Gson library for first time. I am making an HTTP request and pulling response (JSON response) and need to pull a specific result.
StringBuilder response;
try (BufferedReader in = new BufferedReader( new InputStreamReader(connection.getInputStream()))) {
String line;
response = new StringBuilder();
while((line = in.readLine()) != null) {
response.append(line);
}
}
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.create();
System.out.println(gson.toJson(response));
The response looks like this below, and I need to pull only cardBackId:
[{\"cardBackId\":\"0\",\"name\":\"Classic\",\"description\":\"The only card back you\u0027ll ever need.\",\"source\":\"startup\",\"sourceDescription\":\"Default\",\"enabled\":true,\"img\":\"http://wow.zamimg.com/images/hearthstone/backs/original/Card_Back_Default.png\",\"imgAnimated\":\"http://wow.zamimg.com/images/hearthstone/backs/animated/Card_Back_Default.gif\",\"sortCategory\":\"1\",\"sortOrder\":\"1\",\"locale\":\"enUS\"
You could use JSONPath (which is a Java library for selecting parts of a JSON object) to extract just the part you need from the string.
Alternatively, you could write a class that only contains the field you want:
public class CardBackIdResponse {
public int cardBackId;
}
And then use Gson to unmarshall the JSON into your object:
CardBackIdResponse[] cardBackIdResponses = gson.fromJson(response.toString(), CardBackIdResponse[].class);
System.out.println("cardBackId = " + cardBackIdResponses[0].cardBackId);
When unmarshalling an object from JSON, if Gson cannot find a field in the object to populate with a value from the JSON, it will just discard the value. That's the principle we could use here.
Edit: Altered answer above to handle JSON array as per this SO question.

How to add json to GET request query parameter?

I want json to be sent to GET request in query parameter to get the response for that json request.
If I use a link something like this :
www.url.com/search?query1=abc&filter={"or":[{"terms":{"vin":["1g1105sa2gu104086"]}}]}
Then the url part appears blue if I do it as sysout statement, something like this:
www.url.com/search?query1=abc&filter={"or":[{"terms":{"vin":["1g1105sa2gu104086"]}}]}
and the json appears as if it is not the part of the request.
To create a URL, I'm appending the manipulated JSON string to the URL and then sending the request. But it appears as two different strings.
Also I have used encoder to encode the JSON part
filter={"or":[{"terms":{"vin":["1g1105sa2gu104086"]}}]}
In that case the brackets and double quotes everything in that json is encoded, even the equalTo sign. Also the link appears blue but while sending request it throws exception of 400 Bad Request, since the equalTo is also converted to its encoding format.
I tried encoding only the JSON part leaving the filter= in the url itself, something like this :
www.url.com/search?query1=abc&filter={"or":[{"terms":{"vin":["1g1105sa2gu104086"]}}]}
The results that appear after the request is send is different from the results I want.
I'm using following code to create a JSON:
private String getVinFromInventoryRequest(String vin) throws JSONException {
JSONObject request = new JSONObject();
JSONArray orArray = new JSONArray();
for(String vin : vins) {
JSONObject termsObject = new JSONObject();
JSONObject vinsObject = new JSONObject();
JSONArray vinsArray = new JSONArray();
vinsArray.put(vin);
vinsObject.put("vin", vinsArray);
termsObject.put("terms", vinsObject);
orArray.put(termsObject);
}
request.put("or", orArray);
System.out.println("OfferMapper.getVinFromInventoryRequest " + request.toString());
return request.toString();
}
Also look what I found with a little googling :
JSONObject json = new JSONObject();
json.put("someKey", "someValue");
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params = new StringEntity(json.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
httpClient.execute(request);
// handle response here...
} catch (Exception ex) {
// handle exception here
} finally {
httpClient.close();
}
For more info see : HTTP POST using JSON in Java

How to read resulting JSON data into Java ?

I am trying to read results of a JSON request into java, yet
The partial output of my JSON request looks like this :
"route_summary": {
"total_distance": 740,
"total_time": 86,
"start_point": "Marienstraße",
"end_point": "Feldbergstraße"
}
I would like to use the standard json library to extract the values in total_distance.
However I only seem to be able to get the 'route_summary' by doing this :
JSONObject json = null;
json = readJsonFromUrl(request);
json.get("route_summary");
Where
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
What I want is get 'into' route_summary, any clue / tip would be great !
You need to get route_summary, as you already did, and from that object you need to get the total_distance. This will give you back the route_summary.total_distance.
Code sample:
JSONObject object = new JSONObject(s);
int totalDistance = object.getJSONObject("route_summary").getInt("total_distance");
I would recommend you to use GSON library. You can create class which will represent the message and then automatically map JSON to object by invoking function: gson.fromJson(message, YourMessageClass.class).getRoute_summary().
Here is the example of such approach: https://sites.google.com/site/gson/gson-user-guide/#TOC-Object-Examples

Categories