How can I replace values in a JSON object in java?
How can I replace values in a JSON object in java?
This is the initial json data.
{"type":"record", "users":[{"name":"user1","type":"string"},{"name":"user2","type":"string"},{"name":"user3","type":"string"}]}
I need to replace the values in "users" with the following value.
{"user":"user4","type":"string"}
Final output should be:
{"type":"record", "users":[{"user":"user4","type":"string"}]}
Is there a direct method for this in Java?
Right now I am just emptying the original json object using 'for' loop and 'remove()' and add the string after converting it to json object using 'put()'.
JSONArray jarray = new JSONArray();
jarray = jsonobj.getJSONArray("users"); //jsonobj is the original json object
for(int i=0; i<jarray.length(); i++)
{
jsonobj.getJSONArray("users").remove(i);
}
jsonobj.getJSONArray("users").put(0,new_jsonobj);
//new_jsonobj contains the string
do you have a class matching this json? how are you recieving this json and from where?
– pvpkiran
Jun 29 at 9:13
Another option would be to use a regex
– Lino
Jun 29 at 9:19
Please showcase what you have tried. Also, as a general question, you can deserialize the json into a map and update the value.
– Sid
Jun 29 at 9:20
It looks like you want us to write some code for you. While many users are willing to produce code for a coder in distress, they usually only help when the poster has already tried to solve the problem on their own. A good way to demonstrate this effort is to include the code you've written so far, example input (if there is any), the expected output, and the output you actually get (console output, tracebacks, etc.). The more detail you provide, the more answers you are likely to receive. Check the FAQ and How to Ask.
– lexicore
Jun 29 at 9:21
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
use a json parser, parse the string, replace the value with your custom value, create a json out of it again
– Lino
Jun 29 at 9:11