If Gson is like Jackson (I assume so) you'll have to first get the JsonObject "accounts" from the root object and then remove the member "email", e.g. like this:
jsonObj.getAsJsonObject("accounts").remove("email");
Alternatively - and probably the preferred way - you would map the json object to a POJO (one that has the fields "status", "accounts" and "accounts" would point to another POJO), navigate to the accounts-POJO and set "email" to null there. Then you reformat the root POJO to JSON and apply a setting that omits fields with null values.
Edit (answer to the question in the comment):
To make it short, I don't know whether there is a built-in functionality or not but it should be doable.
The problem is that if you just provide keys like email etc. you might get situations where there are multiple keys so identifying the correct one could be hard. Thus it might be better to provide the key as accounts.email and split the "key" into sub-expressions and then traverse the Json tree using the parts or convert the Json to a POJO and use some expression language (e.g. Java EL or OGNL) to traverse the POJO.
If you want to remove all properties named email you could just travers the entire json tree, check whether there is a property with that name and if so remove it.
If Gson is like Jackson (I assume so) you'll have to first get the JsonObject "accounts" from the root object and then remove the member "email", e.g. like this:
jsonObj.getAsJsonObject("accounts").remove("email");
Alternatively - and probably the preferred way - you would map the json object to a POJO (one that has the fields "status", "accounts" and "accounts" would point to another POJO), navigate to the accounts-POJO and set "email" to null there. Then you reformat the root POJO to JSON and apply a setting that omits fields with null values.
Edit (answer to the question in the comment):
To make it short, I don't know whether there is a built-in functionality or not but it should be doable.
The problem is that if you just provide keys like email etc. you might get situations where there are multiple keys so identifying the correct one could be hard. Thus it might be better to provide the key as accounts.email and split the "key" into sub-expressions and then traverse the Json tree using the parts or convert the Json to a POJO and use some expression language (e.g. Java EL or OGNL) to traverse the POJO.
If you want to remove all properties named email you could just travers the entire json tree, check whether there is a property with that name and if so remove it.
Alternatively, you can use below:
DocumentContext doc = JsonPath.parse(json);
doc.delete(jsonPath);
Where json and and jsonPath are strings.
Library: com.jayway.jsonpath.DocumentContext.
You have to use remove("OLD_KEY") to remove value and then add this under new key
As already answered by Konstantin Pribluda, you remove the old key by calling remove. Since that returns the removed value, you can use it directly.
Here is an MCVE (Minimal, Complete, and Verifiable example), tested using org.json:json:20140107:
import org.json.JSONObject;
String json = "{" +
" \"Foo\": \"Bar\"," +
" \"MYKEY\": [ 1, 2, 3, 4 ]" +
"}";
JSONObject myObj = new JSONObject(json);
System.out.println(myObj);
myObj.put("MYNEWKEY", myObj.remove("MYKEY"));
System.out.println(myObj);
Output
{"MYKEY":[1,2,3,4],"Foo":"Bar"}
{"Foo":"Bar","MYNEWKEY":[1,2,3,4]}
As you can see, the MYKEY property was renamed to MYNEWKEY.
jsonObj.getJSONArray("Data").get(0).remove("status);
#Updated Code-breakdown:
JSONObject obj= (JSONObject) jsonObj.getJSONArray("Data").get(0);
obj.remove("status");
JSONArray newArr=new JSONArray();
newArr.put(obj);
jsonObj.put("Data", newArr);
It should do your work, haven't tested though.
First, your Data is JSONArray, retrieving that by jsonObj.getJSONArray("Data"), then access the array with get(0)[assuming, your array will contain only one entry like your example] and finally, removing that key by remove method.
You need to iterate over Data property which is a JSON Array and remove for every item status key.
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.File;
import java.io.FileReader;
public class JsonSimpleApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
JSONParser parser = new JSONParser();
JSONObject root = (JSONObject) parser.parse(new FileReader(jsonFile));
JSONArray dataArray = (JSONArray) root.get("Data");
dataArray.forEach(item -> {
JSONObject object = (JSONObject) item;
object.remove("status");
});
System.out.println(root);
}
}
Above code prints:
{"Data":[{"Id":"1358","isActive":true}],"actionName":"test"}
I wouldn't recommend using regex for such thing, the better choice would be using a library for parsing json, remove the value, and then turn it into a string again.
JSONObject jsonObject = new JSONObject(input);
jsonObject.getJSONObject("expressions").remove("storyId");
String output = jsonObject.toString();
if you really want to use regex, you can use the follow
jsonString.replaceAll("(\\\"storyId\\\"|\\'storyId\\')\\s*:\\s*(\\\"[^\\\"]*\\\"|'[^\\\"]*')\\s*,?", "");
but just make sure that storyId is really a string, otherwise this regex won't work.
edit: updated my answer, if you want a function that get the parameter to remove with regex,
void replaceAllKeys(String keyName, String jsonAsString) {
String pattern = String.format("(\\\"%s\\\"|\\'%s\\')\\s*:\\s*(\\\"[^\\\"]*\\\"|'[^\\\"]*')\\s*,?", keyName, keyName);
return jsonAsString.replaceAll(pattern, "");
}
First i am assuming you will get all json object in jsonObj and then call remove() by passing your json key like following:
jsonObj.getAsJsonObject("expressions").remove("storyId");
Iterator keys = detailJSON.keys();
while(keys.hasNext())
detailJSON.remove((String)detailJSON.keys().next());
this version has an overhead because of getting the key-set everytime, but it works without concurrent modification exception.
while(json.length()>0)
json.remove(json.keys().next());
org-json-java can do the things you want
import org.json.JSONException;
import org.json.JSONObject;
public class JsonTest {
public static void main(String[] args) {
try {
JSONObject testObject = new JSONObject("{\"a\":\"vala\", \"b\":\"valb\", \"c\":\"valc\"}");
testObject.remove("b");
testObject.remove("c");
System.out.println(testObject.toString()); // This prints out the json string
} catch (JSONException e) {
e.printStackTrace();
}
}
}
The execution result is
{"a":"vala"}
Make sure you've downloaded and imported org.json-YYYYMMDD.jar from here before you run the above code.
Firstly I think you need change title of question.
Secondly, If you want change from String to Json just using org.json library
JSONObject jsonObj = new JSONObject("{\"a\":\"valuea\",\"b\":\"valueb\"}");
Are you tried remove. http://www.json.org/javadoc/org/json/JSONObject.html#remove(java.lang.String)
Json.remove(key)
You can do something like this. This will iterate and remove each matched key.
private static void iterateJSONAndRemoveKey(JSONObject jObj) {
Set<String> keys = jObj.keySet();
for(String key : keys) {
if(key.equals("remove_me")) {
jObj.remove(key);
}
else if(jObj.get(key) instanceof JSONObject) {
JSONObject subObject = (JSONObject) jObj.get(key);
iterateJSONAndRemoveKey(subObject);
}
else if(jObj.get(key) instanceof JSONArray) {
JSONArray jArray = (JSONArray) jObj.get(key);
for(int i = 0; i < jArray.size(); i++) {
if(jArray.get(i) instanceof JSONObject) {
iterateJSONAndRemoveKey((JSONObject)jArray.get(i));
}
}
}
}
}
As I was using com.fasterxml.jackson Library, Below is the solution.
private static void iterateJSONAndRemoveKey(JsonNode rootNode,String toRemove) throws Exception {
Iterator<String> keysIterator = rootNode.fieldNames();
while (keysIterator.hasNext()) {
String key = keysIterator.next();
if (key.equalsIgnoreCase(toRemove)){
((ObjectNode) rootNode).remove(toRemove);
return;
}else if (rootNode.isObject()){
iterateJSONAndRemoveKey(rootNode.get(key),toRemove);
}else if (rootNode.isArray()){
ArrayNode arrayNode = (ArrayNode) rootNode;
for (JsonNode node : arrayNode) {
iterateJSONAndRemoveKey(node,toRemove);
}
}
}
}
Asked answer helped me to write the logic in Jackson library.
You can remove any element by using JsonObjectBuilder.
For example:
public class Test{
public static void main(String[] args) {
javax.json.JsonObject full = javax.json.Json.createObjectBuilder().add("a", 1).add("b", 2).build();
full = javax.json.Json.createObjectBuilder(full).remove("a").build();
System.out.println(full); // return {"b":2}
}
}
JsonObject is immutable. So, you can create a new object with or without a property.
To remove a property:
public static JsonObject removeProperty(JsonObject origin, String key){
JsonObjectBuilder builder = Json.createObjectBuilder();
for (Map.Entry<String,JsonValue> entry : origin.entrySet()){
if (entry.getKey().equals(key)){
continue;
} else {
builder.add(entry.getKey(), entry.getValue());
}
}
return builder.build();
}
And to add a new property:
public static JsonObject addProperty(JsonObject origin, String key, String value){
JsonObjectBuilder builder = Json.createObjectBuilder();
for (Map.Entry<String,JsonValue> entry : origin.entrySet()){
builder.add(entry.getKey(), entry.getValue());
}
builder.add(key, value);
return builder.build();
}