It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a JSON coming from server as below
{
"XXXX": {
"type": "RSS",
"value": ""
},
"YYYY": {
"type": "String",
"value": ""
},
"ZZZZ": {
"type": "String",
"value": ""
}
}
Now I need to add the String value in fields of all XXXX, YYYY, and ZZZZ.
I'm using eclipse and I need to change the value of "value" in XXXX and YYYY and ZZZZ and I need to add the field
{
"MMMM": {
"type": "Image",
"value": "a7e8bec0-87ed-11e2-aa2e-52540025ab96_2_1362746556"
}
}
After ZZZZ. Please let me know how to do it.
Try this
String jsonstring="{
"XXXX": {
"type": "RSS",
"value": ""
},
"YYYY": {
"type": "String",
"value": ""
},
"ZZZZ": {
"type": "String",
"value": ""
}
}";
JSONObject object=new JSONObject(jsonstring);
JSONObject childobject=object.getJSONObject("XXXX");
JSONObject modifiedjson=new JSONObject();
modifiedjson.put("type",childobject.get("type"));
modifiedjson.put("value","newvalue"); // Add new value of XXXX here
//
JSONObject mmjson=new JSONObject();
mmjson.put("type","image");
mmjson.put("value","a7e8bec0-87ed-11e2-aa2e-52540025ab96_2_1362746556"); // Add new value of MMM here
JSONObject newjson=new JSONObject();
newjson.put("MMMM",mmjson.toString());
newjson.put("XXXX",modifiedjson.toString());
newjson.put("YYYY",object.get("YYYY"));
newjson.put("ZZZZ",object.get("ZZZZ"));
I think you meant
{"XXXX":
{"type":"RSS","value":"},
"YYYY (mins)":{"type":"String","value":""},
"ZZZZ":{"type":"String","value":""}
is the JSON you get from server. You can always get the JSONObject.toString and edit it as required and then do something like,
JSONObject obj = new JSONObject(myString);
If you need to add a key value to JSON you may try,
JSONObject value = new JSONObject();
value.put("key","value");
value.put("key","value");//add all the field you want for ZZZZ.
obj.put("ZZZZ",value);
If it is a string, you can just search for the specified values and concat the new string.
If it is a JSON Object, you could add new Values to the JSON Object and search for the values you want to manipulate and set them new.
What are you doing at the moment? Can you show us some code, so we know, where exactly you have the problem? And show, how you are accessing the JSON in this code, please.
User Java String replacement method to replace string.
Take you Json as a string then replace value via string replacement method.
Here is small example.
String replaceSample = "This String replace Example shows how to replace one char from
String newString = replaceSample.replace('r', 't');
Thanks.
var source={
"XXXX": {
"type": "RSS",
"value": ""
},
"YYYY": {
"type": "String",
"value": ""
},
"ZZZZ": {
"type": "String",
"value": ""
}
}
And element you wanted to add
var element={
"type": "Image",
"value": "a7e8bec0-87ed-11e2-aa2e-52540025ab96_2_1362746556"
};
You can do with below script,
source["MMMM"]=element;
or
source.MMMM=element;
You can do all operations in JavaScript itself.
Lets store the date coming from server into variable a:
var a = {
"XXXX":{"type":"RSS","value":"},
"YYYY (mins)":{"type":"String","value":""},
"ZZZZ":{"type":"String","value":""}
}
To change the value:
a['XXXX']['value'] = 'new_value1';
a['YYYY']['value'] = 'new_value2';
a['ZZZZ']['value'] = 'new_value3';
To add a field:
a["MMMM"] = {"type":"Image","value":"a7e8bec0-87ed-11e2-aa2e-52540025ab96_2_1362746556"}}
Related
I have a Json body like the example below. I need to extract the value from a key that has another key with a specific value in an array. I am passing in a JsonNode with everything in the detail component of the message, I can easily extract from each level, however, I'm struggling with the array.
In this case, I need to extract the value of "value" (Police/Fire/Accident Report) from the object in the array which has a key/value pair of "name":"documentTitle". I understand this is a JSONArray, but I can't find a good example that shows me how to extract the values for an object in the array that contains a certain key/value pair, I don't think I can rely on getting the object in position [2] in the array as the same objects may not always be present in the additionalMetadata array.
Sample Json:
"sourceVersion": "1.0",
"eventId": "8d74b892-810a-47c3-882b-6e641fd509eb",
"clientRequestId": "b84f3a7b-03cc-4848-a1e8-3519106c6fcb",
"detail": {
"stack": "corona",
"visibilityIndicator": null,
"documentUid": "b84f3a7b-03cc-4848-a1e8-3519106c6fcb",
"additionalMetadata": [
{
"name": "lastModifiedDate",
"value": "2021-05-21T04:53:53Z"
},
{
"name": "documentName",
"value": "Police/Fire Report, 23850413, 2021-05-20 14:51:23"
},
{
"name": "documentTitle",
"value": "Police/Fire/Accident Report"
},
{
"name": "documentAuthor",
"value": "System Generated"
},
{
"name": "lastModifiedBy",
"value": "System Updated"
},
{
"name": "createdBy",
"value": "System Generated"
},
{
"name": "documentDescription",
"value": "Police/Fire Report received"
},
{
"name": "organizationCode",
"value": "Claims"
}
]
}
}```
Loop through the json array and extract the json object with name documentTitile. From that json object you can get the value
Well, either the JSON framework you're using supports this out of the box (check the documentation) or you could convert it manually to a map:
List<AdditionalMetadataEntry> additionalMetadata;
[...]
Map<String, String> additionalMetadataMap = additionalMetadata.stream().collect(Collectors.toMap(AdditionalMetadataEntry::getName, AdditionalMetadataEntry::getValue));
I was able to figure it out. I created a new node off the existing notificationBody JsonNode, then parsed through the metadata key/value pairs:
String docTitle = "";
JsonNode additionalMetadata = notificationBody.get("detail").get("additionalMetadata");
for (JsonNode node: additionalMetadata) {
String name = node.get("name").asText();
String value = node.get("value").asText();
if(name.equals("documentTitle")){
docTitle = value;
}
}
I am looking for some Java library, which can convert below give String into Json object.
Input: String reading from file.
{ "product": "{\"sku\":\"rtwre-rtwe\",\"price\":\"50.90\",\"currency_code\":\"SGD\",\"quantity\":1}", "is_organic": "0", "can_claim": "0", "t": "r", "device": "Phone", "amount_transactions": "0" }
Expected output: In some generic Java Json object.
{
"product": {
"sku": "rtwre-rtwe",
"price": "50.90",
"currency_code": "SGD",
"quantity": 1
},
"is_organic": "0",
"can_claim": "0",
"t": "r",
"device": "Phone",
"amount_transactions": "0"
}
Imp points: This is sample code, I have more dynamic json and don't have any Java object corresponding to my json. I can have string json in any key. It's not specific to particular key. I am looking for more generic code.
Here my goal if I read value of key "product" it should return Json instead of String. I want to read $.product.price using JsonPath library. http://jsonpath.com/
Edit1: I don't have much experience with Gson, Jackson and JsonObject libraries, but I tried whatever I could do. If you had handled the same scenario, please help me out.
To resolve it you can use :
JSONObject jsonObj = new JSONObject(myStringValue);
String myJsonStructureAsString = jsonObj.toString();
Where JSONObject is org.json.JSONObject form lib json-org.v2017.05.16.jar
I have a Java Spring MVC Web Application. I am trying to implement a form submission where the user will be submitting the form and an email would be sent to the user with the form data. I will receive the form data as JSON string. But the email sent with this data doesn't look readable. I have tried the following code to make the data more readable, but doesn't seem to make much difference:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(jsonData);
String message = gson.toJson(je);
My JSON String looks something like below:
[ { "name": "FirstName", "value": "Abcd" }, { "name": "LastName", "value": "Efgh" }, { "name": "Email", "value": "test.mail#test.com" }, { "name": "PhoneNumber", "value": "9876543210" }, { "name": "Selected Locations", "value": " loc1, loc2, loc3" }, { "name": "Message", "value": "Hi" }, { "name": "g-recaptcha-response", "value": "03AMPJSYULxjYiDRiNxcOSVYxXR9F8dX5pqIYAZ6_F2igAwGvanS4Vh1Lm47ByS2qGELQ9W1h" } ]
I am looking for an option at least to bring name-value pair into separate lines so that it is in some readable manner when received through an email. Is there any way to do this. The form can be generic, SO I may not be able to map this string to any Java object.
I have already tried the following link and the solution does not work for me:
Pretty-Print JSON in Java
I also don't see many helpful details online regarding this. I am trying to put each name-value pair in a new line of the generated string to send the data as email.
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 6 years ago.
{
"Header": {
"AppId": "appiddfdsf324",
"RecId": "fdsfrecid79878_879898_8797",
"SecureRefId": "fsdf5679567fsd_6789678",
"Type": "Other",
"Ver": "9.0.0",
"StartTS": "2016-09-26:07:48.798798-04:00"
},
"Application": {
"APP_OS": "Windows",
"APP_Runtime": ".Net67986",
"APP_AppName": "MPS",
"APP_AppVersion": "9.0.0.0",
"Host": "fsdhajkfh657895fsdajf",
"Channel": "N/A",
"APP_ReqId": "2f3d7987987-78987-987987-897-da"
},
"Service": {
"Key": "modification process",
"CallType": "HGDL",
"Operation": "processrequest",
"Port": "n/a"
},
"Results": {
"Elapsed": 0,
"Message": "Message Succesfully Deleted",
"TraceLevel": "Information"
},
"Security": {
"Vendor": "abfsdf"
},
"Extended_Fields": {
"CustomerId": "4564987987",
"MessageId": "768789fsdafasdf987987987fasdf",
"TimeElapsed": "1272.8171"
}
}
in above string value we are capturing from website result values we will get in a string format by using selenium webdriver.
This i need to convert and read value of "Message"
Note : i have tried below code
JsonElement jelement = new JsonParser().parse((String) elementText);
JsonObject jobject = jelement.getAsJsonObject();
jobject.getAsJsonObject("Results");
This above will provide complete result value of Result json but i required to fetch values which is present with "Message"
Below first line creates the JSONObject by passing String [which is of JSON format and it should be in JSON format, otherwise it will through an exception]
In Second line , as you have a JSON Object now, you can fetch any element from that,
e.g to fetch the value for Message, which is an element of "Results" object which is of JSON type,
we can access any element by using . and depending on what are you fetching use get
e.g getString -> for getting String,
getInt->for getting Integer,
JSONObject-> for getting an JSONObject
getJSONArray-> for getting a JSONArray
JSONObject jsonObj=new JSONObject(pass your String) //This converts in to JSON Object
jsonObj.getJSONOObject("Results").getString("Message"); //As result internally itself is a JSON Object
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 9 years ago.
Iam new to java script and JSON, please help me in solving my problem. Below is the structure of my JSON in JavaScript
{
"name": "sample",
"def": [
{
"setId": 1,
"setDef": [
{
"name": "ABC",
"type": "STRING"
},
{
"name": "XYZ",
"type": "STRING"
}
]
},
{
"setId": 2,
"setDef": [
{
"name": "abc",
"type": "STRING"
},
{
"name": "xyz",
"type": "STRING"
}
]
}
]
}
in the backend, what should be the synatx of java method to receive this data
public void getJsonData(****){
}
How to parse this JSON data in java and what should be the syntax of method parameter ?
update 1: Edited the json format to make it valid
First create a class that will map your json object and give a name something like "DataObject". Then use the gson library and do the following:
String s = "";
DataObject obj = gson.fromJson(s, DataObject.class);
Your JSON is invalid, but assuming you fix that then you are looking for a library in Java which will serialize an annotated Java class to JSON, or deserialize JSON data to an annotated Java class.
There is a whole list of suitable libraries here:
http://json.org/java/