How to replace value in json file
You can try this with simple json library(library) . I am separately printed all object for understanding. AS you declare Id object inside two more object, so firstly you have to get this object then get your desire object IDNew. Then put new id value in id field.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class Main {
private static final String filePath = "E:\\project-test\\scloud\\test\\src\\main\\resources\\test";
public static void main(String[] args) {
try {
// read the json file
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
System.out.println(jsonObject);
JSONObject addedObj = (JSONObject) jsonObject.get("Added");
System.out.println("Added is: " + addedObj);
JSONObject newmemObject =(JSONObject) addedObj.get("newmem");
System.out.println("newmemObject is: " + newmemObject);
JSONObject idNewObj =(JSONObject) newmemObject.get("IDNew");
System.out.println("IdNewObj is: " + idNewObj);
long id =Long.valueOf((String) idNewObj.get("id"));
System.out.println(id);
idNewObj.put("id",809809809);
System.out.println(jsonObject);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} catch (ParseException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
}
}
Or for simplicity you can use this
FileReader reader = new FileReader(filePath);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
System.out.println(jsonObject);
JSONObject idObj = (
(JSONObject) (
(JSONObject) (
(JSONObject)
jsonObject.get("Added")
).get("newmem")
).get("IDNew")
);
idObj.put("id", 98009809);
System.out.println("After ID value updated : "+jsonObject);
How to modify values of JsonObject / JsonArray directly?
Strangely, the answer is to keep adding back the property. I was half expecting a setter
method. :S
System.out.println("Before: " + obj.get("DebugLogId")); // original "02352"
obj.addProperty("DebugLogId", "YYY");
System.out.println("After: " + obj.get("DebugLogId")); // now "YYY"
Update inner object element in Json using Gson
Updated code slightly and pass parameters as suggested by @Smile answer
keyPath : reqParams/headerId
someId (if exist in root level)
Code :
public String updateValue(String keyPath, String updateText, String jsonText) {
String[] keys = keyPath.split("/");
JsonParser jsonParser = new JsonParser();
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonText);
JsonObject returnVal = jsonObject; // This holds the ref to target json object
JsonPrimitive jp = new JsonPrimitive(updateText);
String finalKey = keys[keys.length - 1];
for (String key : keys) {
if (jsonObject.get(key) != null && jsonObject.get(key).isJsonObject()) {
jsonObject = (JsonObject) jsonObject.get(key);
jsonObject.remove(finalKey);
jsonObject.add(finalKey, jp);
return returnVal.toString();
} else if (jsonObject.get(finalKey) == null) {
return returnVal.toString();
}
}
jsonObject.remove(finalKey);
jsonObject.add(finalKey, jp);
return returnVal.toString();
}
How to modify values of JsonObject
How about something like this?
private static void statDup(final JSONObject o) {
if (o.containsKey("properties")) {
final JSONArray a = (JSONArray) o.get("properties");
for (final Object e : a) {
final JSONObject p = (JSONObject) e;
p.put(p.get("stat"), p.get("data"));
}
} else {
for (final Object key : o.keySet()) {
final Object value = o.get(key);
if (value instanceof JSONArray) {
for (final Object e : (JSONArray) value) {
statDup((JSONObject) e);
}
}
}
}
}
Update json element in json object
You need to look for the USDT-BTC and change the price:
for (var i in json.result) {
var item = json.result[i];
if (item.MarketName == 'USDT-BTC') {
item.Price = 17000.00000001;
}
}
Other way using map:
json.result = json.result.map(item => (
item.MarketName == 'USDT-BTC' ?
{ ...item, price: 17000.00000001} : item );
)
updating a JSON object in a list of JSON objects
In React you can't update state directly. so by doing
let todos = [...this.state.todos];
It create a copy of the todos
property which is in the state and It doesn't reference to the value which is in the state.
let todoId = 2;
let todos = [
{id: 1, name: "todo 1", done: false},
{id: 2, name: "todo 1", done: false},
{id: 3, name: "todo 1", done: false}
]
let todo = todos.find((todo) => todo.id == todoId);
// if I update any attribute of the previous toto variable it will also update it value in the `todos`
todo.name = "updated todo name";
console.log(todos);
How to edit, modify nested JSONObject
I found solution.
public static JSONObject setProperty(JSONObject js1, String keys, String valueNew) throws JSONException {
String[] keyMain = keys.split("\\.");
for (String keym : keyMain) {
Iterator iterator = js1.keys();
String key = null;
while (iterator.hasNext()) {
key = (String) iterator.next();
if ((js1.optJSONArray(key) == null) && (js1.optJSONObject(key) == null)) {
if ((key.equals(keym))) {
js1.put(key, valueNew);
return js1;
}
}
if (js1.optJSONObject(key) != null) {
if ((key.equals(keym))) {
js1 = js1.getJSONObject(key);
break;
}
}
if (js1.optJSONArray(key) != null) {
JSONArray jArray = js1.getJSONArray(key);
for (int i = 0; i < jArray.length(); i++) {
js1 = jArray.getJSONObject(i);
}
break;
}
}
}
return js1;
}
public static void main(String[] args) throws IOException, JSONException {
FileInputStream inFile = new FileInputStream("/home/ermek/Internship/labs/java/task/test5.json");
byte[] str = new byte[inFile.available()];
inFile.read(str);
String text = new String(str);
JSONObject json = new JSONObject(text);
setProperty(json, "rpc_server_type", "555");
System.out.println(json.toString(4));
How to update a nested JSON object in JSON file using Java?
Arrays in JSON simple are classes of the type JSONArray (this is just a java util ArrayList), so once you get the array and the object (this is a java util HashMap) you can modify it.
JSONArray users = (JSONArray) JSONValue.parse(json);
JSONObject firstUser = (JSONObject) users.get(0);
JSONArray firstUserGoals = (JSONArray) firstUser.get("Goals");
JSONObject firstUserFirstGoal = (JSONObject) firstUserGoals.get(0);
JSONArray firstUserFirstGoalMilestones = (JSONArray) firstUserFirstGoal.get("milestones");
JSONObject firstUserFirstGoalFirstMilestone = (JSONObject) firstUserFirstGoalMilestones.get(0);
So you can edit a milestone
firstUserFirstGoalFirstMilestone.put("milestoneName", "Chapter 0");
You can create a new milestone
JSONObject milestone1 = new JSONObject();
milestone1.put("milestoneName", "Chapter 1");
milestone1.put("Difficulty", "H");
milestone1.put("dueDate", "02/18/2018");
milestone1.put("completed", true);
Then add it to the milestones list, at position 1. If no index is specified is added at last.
firstUserFirstGoalMilestones.add(1, milestone1);
Finally you can get the JSON as string.
String finalJson = users.toJSONString();
Or write to file (exceptions should be handled)
Writer writer = new FileWriter(path);
users.writeJSONString(writer);
writer.close();
Related Topics
Error While Running Allure Command Line Generate Command
Javac: File Not Found: First.Java Usage: Javac <Options> <Source Files>
How to Get a Resource Id With a Known Resource Name
Splitting a String Containing Special Characters in to Individual Characters
Generating Unique Random Numbers Effectively in Java
Search Particular Column Value from CSV File Using Java
How to Convert Xml to Java.Util.Map and Vice Versa
Newline Character in Jlabel.Settext()
Password Encrypt and Decrypt Using Spring-Security
Correct Way to Implement Http Connection Pooling
Calculating the Angle Between Two Lines Without Having to Calculate the Slope (Java)
Java Simpledateformatter With 10 Decimals After the Seconds, Cannot Convert to Date
Spring Data JPA Saveall Not Doing Batch Insert
Setting Custom Key When Pushing New Data to Firebase Database
In Java How to Extract Exact Domain Name from Url
I Get a Status 200 When Connecting to the Websocket, But It Is an Error