How can i convert this JSON to Java Object? - java

I'm learning JACKSON. To train my skills i want to get field "URL" from following JSON:
How can i do that? I don't need whole JSON-object, just one field (URL).

You don't need to convert the JSON into a Java Object for that you will need to define POJOS.
Maybe this will help :-
final ObjectNode yourNode = new ObjectMapper().readValue(<Your_JSON_Input_String>, ObjectNode.class);
if (node.has("URL")) {
System.out.println("URL :- " + node.get("URL"));
}

import org.json.JSONArray;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) throws IOException {
String jsonString = "{\"data\":[{\"url\":\"http://example.com\"}]}";
JSONObject jsonObject = new JSONObject(jsonString); // 1
JSONArray data = jsonObject.getJSONArray("data"); // 2
JSONObject objectAtIndex0 = data.getJSONObject(0); // 3
String urlAtObject0 = objectAtIndex0.getString("url"); // 4
System.out.println(urlAtObject0);
}
}
Get JSON object for whole JSON string
Get data as JSON array
Get JSON object at desired index or loop on JSON array of previous step
Get url field of the JSON object

Related

How can I convert each integer/double value to String from JSON data containing nested objects and arrays?

I want to convert each integer/double value to String present in json request before storing in MongoDB database.
There can be multiple fields like amountValue in the json. I am looking for a generic way which can parse json with any number of such attributes value to string. My request will have around 200 fields.
ex: "amountValue": 200.00, to "amountValue": "200.00",
{
"templateName": "My DC Template 14",
"templateDetails": {
"beneficiaryName": "Snow2",
"dcOpenAmount": {
"amountValue": 200.00,
}
}
}
My mongoDB Document is of the form
#Document
public class TemplateDetails {
#Id
private long templateId;
private String templateName;
private Object templateDetail;
}
Because we are storing document in mongodb as an object(Which can accept any type of json request) we dont have field level control on it.
In my controller, converting the request object to json.
This is how I tried. But its not meeting my expectation. It is still keeping the amount value to its original double form.:
ObjectMapper mapper = new ObjectMapper();
try {
String json = mapper.writeValueAsString(templateRequestVO);
System.out.println("ResultingJSONstring = " + json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
Output :
ResultingJSONstring = {"id":null,"userId":"FU.ZONKO","txnType":"LCI","accessIndicator":"Public","templateId":null,"templateName":"My DC Template 14","tags":null,"templateDetails":{"applicantDetail":{"applicantName":"Tom","applicantAddress":{"addressLine1":"Infosys, Phase 2","city":"PUNE","state":"MAHARASHTRA","country":"INDIA","zip":"40039"},"accountId":"Account1234","customerId":"JPMORGAN"},"beneficiaryName":"Snow2","dcOpenAmount":{"amountValue":200.0,"currency":"USD"}}}
Is there any way to accomplish the result ? Or anything which can help to store documents in mongodb with attribute type as String ?
You can use Json manipulation avaliable in "org.json.JSONObject" to convert Double value to Stirng .
If your Json structure won't change and will remain as said above , you can do the following.
import org.json.JSONObject;
public static void main(String args[]) {
String j = "{ \"templateName\": \"My DC Template 14\", \"templateDetails\": { \"beneficiaryName\": \"Snow2\", \"dcOpenAmount\": { \"amountValue\": 200.00 } } }";
JSONObject jo = new JSONObject(j);
jo.getJSONObject("templateDetails")
.getJSONObject("dcOpenAmount")
.put("amountValue", String.valueOf(jo.getJSONObject("templateDetails").getJSONObject("dcOpenAmount").getDouble("amountValue")));
System.out.println(jo.toString());
}
Following will be the output
{"templateDetails":{"dcOpenAmount":{"amountValue":"200.0"},"beneficiaryName":"Snow2"},"templateName":"My DC Template 14"}
I don't know for mongodb but for a json string you can replace them with a regex and the function replace like this :
public class Test {
public static void main(String[] args) {
String json = "{\"id\":null,\"userId\":\"FU.ZONKO\",\"txnType\":\"LCI\",\"accessIndicator\":\"Public\",\"templateId\":null,\"templateName\":\"My DC Template 14\",\"tags\":null,\"templateDetails\":{\"applicantDetail\":{\"applicantName\":\"Tom\",\"applicantAddress\":{\"addressLine1\":\"Infosys, Phase 2\",\"city\":\"PUNE\",\"state\":\"MAHARASHTRA\",\"country\":\"INDIA\",\"zip\":\"40039\"},\"accountId\":\"Account1234\",\"customerId\":\"JPMORGAN\"},\"beneficiaryName\":\"Snow2\",\"dcOpenAmount\":{\"amountValue\":200.0,\"currency\":\"USD\"}}}";
System.out.println(replaceNumberByStrings(json));
}
public static String replaceNumberByStrings(String str){
return str.replaceAll("(?<=:)\\d+(\\.\\d+)?(?=(,|}))","\"$0\"");
}
}
It will look for all fields with a numeric value in the json string and add quotes to the value. This way they will be interpreted as strings when the json willl be parsed.
It will not work if the value is in an array though, but in this case it should not be a problem.

Null pointer observed while trying to fetch the object value from JSON array

I'm trying to loop the calls: JSON array and trying to fetch the machine details JSON object which is present under calls JSON array list as like below:
{
"<dynamicValue>":{
"type":"CORR-ID",
"tags":[
{
"name":"9VB6454145983212H",
"flags":[
"FLAG_DYNAMIC_VALUE",
"FLAG_ID_LOOKUP_SUPPORTED"
]
}
],
"callSummary":[
{
"colo":"lvs",
"pool":"amazon_paymentsplatformserv",
"machine":"stage2utb29958"
},
{
"colo":"lvs",
"pool":"amazon_elmoserv",
"machine":"msmamoserv_0"
},
{
"colo":"lvs",
"pool":"amazon_xopaymentgatewayserv",
"machine":"msmastmentgatewayserv_1"
},
{
"colo":"lvs",
"pool":"amazon_paymentapiplatserv",
"machine":"msmaentapiplatserv_2"
},
{
"colo":"lvs",
"pool":"amazon_userlifecycleserv_ca",
"machine":"stage2utb91581"
},
{
"colo":"lvs",
"pool":"amazon_dafproxyserv",
"machine":"msmasfproxyserv_1"
},
{
"colo":"lvs",
"pool":"paymentserv",
"machine":"te-alm-15757_paymentexecutionserv_0",
"calls":[
{
"colo":"lvs",
"pool":"fimanagementserv_ca",
"machine":"msmgementserv_ca_20"
},
{
"colo":"lvs",
"pool":"fimanagementserv_ca",
"machine":"msmasgementserv_ca_4"
}
]
}
]
}
}
The above JSON file which I stored in String variable and trying to fetch the machine details which is under calls: JSON ARRAY by using below code.
Code:
public static void getHttpUrlformachineList(String response, String CalId, String componentName)
throws Exception
{
//System.out.println(response);
Map<String, String> data = new HashMap<String, String>();
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(response);
JSONObject getValue = (JSONObject) object.get(CalId.trim()); //CalId is the dynamic value that mentioned in the JSON input file
JSONObject getCalSummary = (JSONObject) object.get("callSummary");
JSONArray arrays=(JSONArray) getCalSummary.get("calls");
System.out.println(arrays.size()); // return null pointer
}
Error:
java.lang.NullPointerException: null
at com.online.amazon.hadoop.cal.swagger.utils.Utils.getHttpUrlformachineList(Utils.java:112) ~[classes/:na]
If you notice that calls Array List will not be available in all the callSummary JSON Array, and It will be dynamic and can be available under any component that listed above.
So I just want to dynamically get the calls: JSON array and iterate and fetch machine details.
Can someone help me to achieve this?
Note: I'm using JSON-Simple library to parse and iterate the JSON. It would be great if I get solution on the same.
Updated:
I also tried to create callSummary as JSON array and loop that array to get each JSON object and tried to find the calls but this is also leads to Null pointer.
Also the calls json array is not index specific. It can be anywhere in the payload. It may or may not be there in the payload. I just need to handle if it's exist in any of the component then I need to fetch that machine details
change
JSONArray arrays=(JSONArray) getCalSummary.get("calls");
to
JSONArray arrays= getCalSummary.getJSONArray("calls")
and all other functions where you get objects instead of "get" you should use "getJSONObject", "getString" etc.. then you dont have to cast,
also im pretty sure its not arrays.size() its arrays.length() if you are using package org.json.JSONArray but since key "calls" doesnt exist in every "callSummary" you should check if its null or not before.
You should match the types as specified in your JSON string:
public static void getHttpUrlformachineList(String response, String CalId, String componentName)
throws Exception
{
//System.out.println(response);
Map<String, String> data = new HashMap<String, String>();
JSONParser parser = new JSONParser();
JSONObject object = (JSONObject) parser.parse(response);
JSONObject getValue = (JSONObject) object.get(CalId.trim()); //CalId is the dynamic value that mentioned in the JSON input file
JSONArray getCalSummary = (JSONArray) object.get("callSummary"); // callSummary is a JSONArray, not JSONObject
for (int i = 0; i < getCalSummary.length(); i++) {
JSONObject obj = getCalSummary.getJSONObject(i);
if (obj.has("calls")) {
// grab calls array:
JSONArray callsArray = obj.getJSONArray("calls");
}
}
}
Here, you should also check your JSON values with .has(...) method to avoid getting JSONException if a field doesn't exists in your JSONObject.

Is it possible to maintain ordering in JSON while converting it from xml and vice versa

I need to convert XML to JSON and then after applying some business logic need to reconvert back in XML,
But when i try to convert a XML to JSON and then reconvert back the JSON back to XML I am getting its attributes in Different order.
Eg Following XML
<breakfast_menu><food><name>Belgian Waffles</name><price>$5.95</price></food></breakfast_menu>
is converted to following JSON
{"breakfast_menu":{"food":{"price":"$5.95","name":"Belgian Waffles"}}}
and is reconverted to following XML
<breakfast_menu><food><price>$5.95</price><name>Belgian Waffles</name></food></breakfast_menu>
As there is name tag is replaced by price tag .
Is there any way so that we can maintain ordering so the conversion and reconversion produce same output .
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
public class XmlToJson {
public static int PRETTY_PRINT_INDENT_FACTOR = 4;
public static String TEST_XML_STRING =
"<breakfast_menu>\n" +
"<food>\n" +
"<name>Belgian Waffles</name>\n" +
"<price>$5.95</price>\n" +
"</food>\n" +
"</breakfast_menu>";
public static void main(String[] args) {
try {
JSONObject xmlJSONObj = XML.toJSONObject(TEST_XML_STRING);
String jsonString = xmlJSONObj.toString();
System.out.println(jsonString);
System.out.println("================================");
JSONObject jsonObj = new JSONObject(jsonString);
String s1 = XML.toString(jsonObj);
System.out.println(s1);
s1 = s1.replace("\n", "").replace("\r", "");
TEST_XML_STRING = TEST_XML_STRING.replace("\n", "").replace("\r", "");
System.out.println("================================");
System.out.println(TEST_XML_STRING);
System.out.println("================================");
System.out.println(s1.equals(TEST_XML_STRING));
} catch (JSONException je) {
System.out.println(je.toString());
}
}
}
It might be naturally wrong because by default the definition of JSON is:
An object is an unordered set of name/value pairs.
However, you might want to check JSON.simple library which read the JSON string and keep the order of keys
While there are mechanisms that you might use to provide some sort of ordering, JSON does not guarantee a processor of any particular order. If you are interfacing with some process that requires a particular order (and that is under your control), I would recommend changing that process so it conforms to the normal JSON process to handle unordered input.

Parsing JSON array

I'm using GSON for parsing JSON response.
Unfortunately the WebApi on the server has quite untypical JSON objects.
I need to parse Attachments array from this JSON (there can be more attachments):
{"htmlMessage":"text","Attachments":{"8216096_0":{"content":null,"filename":"plk.jpg","contentType":"image/jpeg","contentDisposition":"attachment","size":86070}}}
Where 8216096_0 is attachments id.
I can't do it with Gson (or I don't know how) so I'm trying to do it with JSONObjects:
// parse attachments
JSONObject attachmentsJson = result.getJSONObject("Attachments");
Then I have one JSONObject with an array of attachments, but I don't know how to get them to the ArrayList from JSONObject because the key value isn't static but generated id..
Thank you
//EDIT:
Thanks to all guys for helping! My final solution looks like this especially thanks to #Jessie A. Morris and his final answer!
List<AttachmentModel> attachmentsList = new ArrayList<AttachmentModel>();
for( Map.Entry<String, JsonElement> attachment : attachments.entrySet()) {
AttachmentModel attachmentModel = new AttachmentModel();
attachmentModel = gson.fromJson(attachment.getValue().getAsJsonObject().toString(), AttachmentModel.class);;
attachmentModel.setmUid(attachment.getKey());
attachmentsList.add(attachmentModel);
}
Okay, I've changed my example a little bit and am certain that this does work correctly (I just tested it):
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* Created by jessie on 14-07-09.
*/
public class TestGson {
private static String JSON = "{\"htmlMessage\":\"text\",\"Attachments\":{\"8216096_0\":{\"content\":null,\"filename\":\"plk.jpg\",\"contentType\":\"image/jpeg\",\"contentDisposition\":\"attachment\",\"size\":86070}}}\n";
public static void main(String[] args) {
JsonObject json = new JsonParser().parse(JSON).getAsJsonObject();
JsonObject attachments = json.getAsJsonObject("Attachments");
List<JsonObject> attachmentsList = new ArrayList<JsonObject>();
for( Map.Entry<String, JsonElement> attachment : attachments.entrySet()) {
attachmentsList.add(attachment.getValue().getAsJsonObject());
}
System.out.println("attachmentsList at the end? " + attachmentsList);
}
}
I'm not completely sure if this really works:
final Map<String,JSONObject> attachmentsJson = (Map<String,JSONObject>) jsonArray.getJSONObject("Attachments");
for(String attachmentId : attachmentsJson.keySet()) {
final JSONObject attachmentJson = attachmentsJson.get(attachmentId);
}
The "Attachments" obj in your example is not an array.
Json arrays are denoted by [....].
"Attachments" is a Json object holding an inner object called "8216096_0".
so to get the inner values do as follows:
JSONObject attachmentsJson = result.getJSONObject("Attachments");
JSONObject inner = attachmentsJson.getJSONObject("8216096_0");
// and interrogate the inner obj:
String content = inner.getString("content");
String filename = inner.getString("filename");
Finally, and for example sake, I will add the code for processing a (real) Json array:
{"htmlMessage":"text",
"Attachments":[{"8216096_0":{"content":null,"filename":"plk.jpg","contentType":"image/jpeg",
"contentDisposition":"attachment","size":86070}},
{"8216096_1":{"content":null,"filename":"plk.jpg","contentType":"image/jpeg",
"contentDisposition":"attachment","size":86070}},
]
}
It will go like this:
JSONArray attachmentsJson = result.getJSONObject("Attachments");
int len = attachmentsJson.length();
for (int i = 0; i < len; i++) {
JSONObject elem = attachmentsJson.getJSONObject(i); // <------ get array element
JSONObject inner = elem.getJSONObject("8216096_0");
// and interrogate the inner obj:
String content = inner.getString("content");
String filename = inner.getString("filename");
}
..Or similar, depending on your Json's exact format.

nameValuePair key added in new JSONObject

When I am building a json object from string it is appended with a root key "nameValuePairs".
String curStr = "{\"e\": \"{}\", \"f\": \"{}\", \"g\": \"{}\"}";
JSONObject oldObj = new JSONObject(curStr);
results to
{"nameValuePairs":{"b":"{}","c":"{}","a":"{}"}}
Why?
Any way to prevent that?
Btw, I am using the string json to represent the actual json which I will use later.
First of all your json is syntactically correct but I guess you wished to represent objects as values, in your case the curly brackets are evaluated as simple strings:
String curStr = "{\"e\": \"{}\", \"f\": \"{}\", \"g\": \"{}\"}";
JSONObject oldObj = new JSONObject(curStr);
using a json like this instead will produce values as objects:
String curStr = "{\"e\": {}, \"f\": {}, \"g\": {}}";
JSONObject oldObj = new JSONObject(curStr);
Anyway, I've tried to create that JSONObject and then print a toString of it, and it will simply print the json, without any accessory name.
As you find out in the comment the problem was given by Gson, that will evaluate the JSONObject as a map. I've tried a little example and I've got "map" as field. Probably I've tried a different version of Gson.
Gson gson = new Gson();
String jsonStr = gson.toJson(oldObj);
result: {"map":{"f":"{}","g":"{}","e":"{}"}}
If you want to create a custom object and deserialize a json with Gson create a class with those properties and use the fromJson(String json, Class clazz) method
public class Test {
private String e;
private String f;
private String g;
}
and
Gson gson = new Gson();
Test myTestObj = gson.fromJson(curStr, Test.class);
Hope this will help you. :)
You can try jsonStringer instead.
Something like below code:
JSONStringer jObject = new JSONStringer()
.object()
.key("UserName").value(userNameValue)
.key("Name").value(nameValue)
.key("EmailId").value(emailIdValue)
.key("CountryId").value(contryIdValue)
.key("CountryName").value("") // It should be blank As Spanish Name is not set if User have App in Spanish
.key("State").value(stateValue)
.key("City").value(cityValue)
.key("ImageByteArray").value(imageBytes)
.endObject();
UPDATE
I have just use your code in my App and check it.
Its showing me the result as we have formed.
Result i am getting is:
{
"f": "{}",
"g": "{}",
"e": "{}"
}
Please check your packages you are importing.
For your reference i am importing below class to represent json object.
import org.json.JSONException;
import org.json.JSONObject;
Just import above class and see the result.
Let me know if you still have any query.

Categories

Resources