My response as below and I want to convert it to json object but I don't know how to do it. Could you guide me? Thank you!
Response:
{"m_list": "[{\"contract\":{\"category\":1,\"cor_num\":101,\"contract_name\":\"ABC\"},\"bu_unit\":{\"bu_name\":\"1-1E\"}}]"}
My expected => It'll convert as a json object as below
{ m_list:
[ { contract:
{ category: 1,
cor_num: 101,
contract_name: 'ABC'},
bu_unit: { bu_name: '1-1E' }} ] }
I tried the following way but seem it didn't work
JSONObject jsonObject = new JSONObject(str)
You can use library Josson to restore the JSON object/array from a string inside a JSON.
https://github.com/octomix/josson
Deserialization
Josson josson = Josson.fromJsonString(
"{\"m_list\": \"[{\\\"contract\\\":{\\\"category\\\":1,\\\"cor_num\\\":101,\\\"contract_name\\\":\\\"ABC\\\"},\\\"bu_unit\\\":{\\\"bu_name\\\":\\\"1-1E\\\"}}]\"}");
Transformation
JsonNode node = josson.getNode("map(m_list.json())");
System.out.println(node.toPrettyString());
Output
{
"m_list" : [ {
"contract" : {
"category" : 1,
"cor_num" : 101,
"contract_name" : "ABC"
},
"bu_unit" : {
"bu_name" : "1-1E"
}
} ]
}
The string you want to convert is not in the JSON format. From the official documentation of JSON https://www.json.org/json-en.html - it has to start with left brace { , and end with right brace }.
Following the comment from #tgdavies if you get the response from some server, ask for clarification. If you just do this yourself, then this string is the correct format for the json file you want.
{"m_list":[{"contract":{"category":1,"cor_num":101,"contract_name":"ABC"},"bu_unit":{"bu_name":"1-1E"}}]}
Related
I am trying to read a json file and after traversing to attrib`s called "paymentKey" and "Session key" and changing their values through JSONObject , the post operation failing.
When i checked the out json after performing above changes it seems that structure is bit unordered , changed and even got to learn that json is not an valid one.
This is bit annoying and not sure how to keep the json format in tag after replacing the attrib`s values.
Below is the Json used
{
"idempotentId": "133215472229",
"customerId": "12345",
"brandId": "ANCHOR",
"sellingChannel": "WEBOA",
"items": [
{
"lineItemId": 123,
"productId": "ANCHOR-WEBOA-640213214",
"price": 1.19,
"quantity": 1,
"modifierGroups": [],
"childItems": [],
"note": " Drink without snacks"
}
],
"fulfillment": {
"email": "12#gmail.com",
"phoneNumber": "+912222621",
"fulfillmentType": "PickUp",
"asap": true,
"pickupFirstName": "Kiran",
"pickupLastName": "Kumar",
"locationId": "33211111"
},
"payment": {
"paymentKey": "12222-444-555-2222-44444121e",
"sessionKey": "02f3waAjHJnVCTstOIu0jcSZfm_1HnGum1lZdsu6iDlLxxjO1FYsG9DHz9130ZzMMkjYY9j5w.7V8CijbmiPSo5ESDsq5hsQ.RpYSS5wkgoSSOMjktEyDTHZh1IPq0wNayp--DE3HE53uUgTEehCvHjSsUP5q8U2ZN1kZXbsufwm_mRCV8hLCrmWVTchhVUTJtmEpyYy142DtSp1ikXOVzGN5i9z_oP5e79QvgmU7_n1C5DeARFRagQClT87vUFBUfleSbLaRyH5v3wkU7ji9URUetcq1iAfS5-cNt6-uJaulFJc2y6uNdn0OtjIe74Hp5G7Gx54VYggduoqx5X1rsCssobfUSJUDLt_vVpz5BvhQM88EaysMAB6EcQHoOnZd_YWrz4IDAAZSwSBUFQAkypVmHo5pbvp64cTDrZE73EYkEwJLGf0dRmedMFe2HiU3DiCr97K3I3KuufxYM_eMRIcn739dntxTq4QePtFdqYGWBzXWQutvvqxWQPbNi7PG_-aauEOzlwJiXG94C8t7NGu0SjB8xHf11Z3orf5Ni4-fRKugY8VJNBl39hnb4-d-g47ut7iuiFDkDHJzlSgt9LFq__CxShG_.YkL2w7QEU85VHjpOj5urieCr4-G"
},
"subTotal": 100.19,
"tax": 4.19
}
Below is the snippet of the code
import org.json.JSONObject;
import org.json.JSONArray;
public JSONObject constructCreateOrderPayload( String freedomPayPaymentKey,String orderInit_SessionKey, String payloadFile) {
String filepath = System.getProperty("user.dir")+"/src/test/resources/JsonFiles/"+payloadFile;
try {
String jsonContents = new String((Files.readAllBytes(Paths.get(filepath))));
JSONObject jsonObject = new JSONObject(jsonContents);
JSONObject payment_obj = (JSONObject) jsonObject.get("payment");
payment_obj.put("paymentKey", freedomPayPaymentKey);
payment_obj.put("sessionKey",orderInit_SessionKey);
System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
System.out.println( " After Changes in JSON OBJECT : ");
System.out.println(jsonObject.toString());
System.out.println("");
System.out.println("-------------------------------------------------------------------------------------------------------------------------------------------------------------------------");
payload = jsonObject; // when i print the json boject the format is displaced hence when validated it says invalid json
} catch (IOException e) {
System.out.println("No file found in the path ");
e.printStackTrace();
}
return payload;
}
When I validated the Json after changes it shows as invalid with errors as shown in below snapshot
I tried a lot but no success, can somebody please look in to issue and advise me where I am going wrong or provide an solution this issue.
JSON in unordered, When you print jsonObject before making the changes you will know the order of the JSON is changed, I have used the Jackson Databind libraries and below is a working code, Change it accordingly
String filepath = "C:\\Users\\wilfred\\Desktop\\Input.json";
try {
String jsonContents = new String((Files.readAllBytes(Paths.get(filepath))));
ObjectMapper mapper = new ObjectMapper();
JsonNode expected = mapper.readTree(jsonContents);
System.out.println("Before converting : " + expected.toString());
JsonNode payment_obj = (expected.get("payment"));
((ObjectNode) payment_obj).put("paymentKey", "Trial1");
((ObjectNode) payment_obj).put("sessionKey", "Trial2");
System.out.println("After converting : " + expected.toString());
} catch (IOException e) {
System.out.println("No file found in the path ");
e.printStackTrace();
}
}
My approach was correct. The only mistake was i had not supply/pass on the correct values to few of the JSon attributes and that resulted in error response.
Rectified as per requirements and was able to get results correctly, hence closing this.
I have a JSON node-like below. The structure of JsonNode will change dynamically.
Now I want to replace/update the value of a particular key.
Sample JSON One
{
"company": "xyz",
"employee": {
"name": "abc",
"address": {
"zipcode": "021566"
}
}
}
Sample JSON Two
{
"name": "abc",
"address": {
"zipcode": "021566"
}
}
I want to replace the zip code value 021566 to 566258. I know key name (zipcode), old and new zip code value but I don't know the path of zip code. I tried multiple ways using com.fasterxml.jackson.databind.JsonNode - put, replace
Is there any way to update in java?
JsonNodes are immutable, but you can find the value you want from a JsonNode, cast the original to an ObjectNode, replace the value, then cast that back to a JsonNode. It's a little odd, I know, but it worked for me.
public static void findAndReplaceJsonNode throws JsonProcessingException {
String jsonOne = "{ \"company\" : \"xyz\", \"address\" : { \"zipcode\" : \"021566\", \"state\" : \"FL\" } }";
String jsonTwo = "{ \"company\" : \"abc\", \"address\" : { \"zipcode\" : \"566258\", \"state\" : \"FL\" } }";
ObjectMapper mapper = new ObjectMapper();
JsonNode nodeOne = mapper.readTree(jsonOne);
JsonNode nodeTwo = mapper.readTree(jsonTwo);
JsonNode findNode = nodeTwo.get("address");
ObjectNode objNode = (ObjectNode) nodeOne;
objNode.replace("address", findNode);
nodeOne = (JsonNode) objNode;
System.out.println(nodeOne);
}
Output:
{"company":"xyz","address":{"zipcode":"566258","state":"FL"}}
Disclaimer: While I do some JSON parsing and processing on a regular basis, I certainly wouldn't say that I'm adept at it or tree traversals with them. There is more than likely a better way to find the value of a child in a JsonNode than by taking the entire child as a node, replacing it's one value and then replacing the node. This should work for you in a pinch, though :)
I am writing Junit test case for my REST service, i am setting the values(below is the piece of code) to get the payload required for REST service
Payload jsonPayload = new Payload ();
payload.setAcc("A");
List<Details> details= new ArrayList<Details>;
Details detail = new Details();
detail.setTotalAmount(1);
detail.setCurrency("dollar");
details.add(detail);
payload.getDetails().addAll(details);
I want JSON to be built in format mentioned below, but I am not getting the JSON as expected, details should be in form of Array.
Required JSON -
{
"Acc" : "A",
"details": [
{
"totalAmount":1,
"currency":"dollar"
}
]
}
Output JSON -
{
"Acc" : "A",
"details":
{
"totalAmount":1,
"currency":"dollar"
}
}
Can anyone help me how can I achieve this?
I want to generate a JSON String in the following structure using Jackson API (JsonFactory,JsonGenerator). How can i do it ?
Expected:
{
"api": {
"Salutaion": "Mr",
"name": "X"
},
"additional": {
"Hello",
"World"
}
}
Actual:
{
"api": "{
\"Salutaion\": \"Mr\",
\"name\": \"X\"
}",
"additional": "{
\"Hello\",
\"World\"
}"
}
The values of the attributes api & additional will be available to me as String. Should i be using writeObjectField (as follows) ?
jGenerator.writeObjectField("api", apiString);
After constructing the jGenerator object, how do i get the final constructed JSON Object's String representation ?
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JsonGenerator jGenerator = jfactory.createJsonGenerator(outputStream);
jGenerator.writeStartObject();
jGenerator.writeObjectField("api", apiString);
jGenerator.writeObjectField("additional", additionalString);
jGenerator.writeEndObject();
jGenerator.close();
outputStream.close();
outputStream.toString()
The outputStream.toString() gives a json string but the double quotes (") in the apiString are getting prefixed with an escape character \
Is this the right way ?
Assuming apiString and additionalString are references to String objects with JSON content, you'll want to write them raw, ie. their content directly. Otherwise, you're serializing them as JSON strings and Jackson will need to escape any relevant characters.
For example
jGenerator.writeFieldName("api");
jGenerator.writeRawValue(apiString);
for api, and the same for additional.
I have a different use case where fields in POJO itself stores JSON data, basically grouping of all data.
Now i want the complete JSON generated from above POJO.
At present i am using this method
private static Gson gson = new Gson();
public static String convertObjectToJSON(Object object) throws Exception {
String jsonResponse = gson.toJson(object);
return jsonResponse;
}
But getting output with escape characters around double quotes like below
{ \"_id\" : 234242, \"name\" : \"carlos\"}
I tried various options in GsonBuilder, but not working.
Basically, i am just grouping multiple JSON data and sending it across.
Could you please do the needful help to get rid of the escape characters around double quotes.
UPDATE:
Question is : I have 3 JSONs and need to combine them into a single JSON and need to pass it to html5 client through Spring MVC. As of now i am added the 3 JSONs into a POJO and trying to convert the same to JSON. Same is explained above.
Thanks & Regards
Venkat
I have tried below sample code and it doesn't have any escape characters around double quotes.
class MyPOJO{
private int _id;
private String name;
// getter & setter
}
String json="{ \"_id\" : 234242, \"name\" : \"carlos\"}";
MyPOJOobj=new Gson().fromJson(json, MyPOJO.class);
System.out.println(new Gson().toJson(obj));
output:
{"_id":234242,"name":"carlos"}
EDIT
If you want to combine 3 JSON string then It will be stored as List of object as illustrated below:
sample code:
String json = "[" +
" { \"_id\" : 1, \"name\" : \"A\"}," +
" { \"_id\" : 2, \"name\" : \"B\"}," +
" { \"_id\" : 3, \"name\" : \"C\"}" +
"]";
Type type = new TypeToken<ArrayList<MyPOJO>>() {}.getType();
ArrayList<MyPOJO> obj = new Gson().fromJson(json, type);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(obj));
output:
[
{
"_id": 1,
"name": "A"
},
{
"_id": 2,
"name": "B"
},
{
"_id": 3,
"name": "C"
}
]