从JsonObject内的Json中删除键 |
您所在的位置:网站首页 › json与jsonobject › 从JsonObject内的Json中删除键 |
百度翻译此文
有道翻译此文
问题描述
I have JsonObject like below {"status":"ACTIVE","accounts":{"email":"[email protected]","name":"Test"}}How can I remove Json key "email" and its value from the JsonObject by using something like jsonObj.remove("email") in java JsonObj.removev working for me if I need to remove status key jsonObj.remove("status") Update Some more background, This is for mainly testing a rest end point. In my test I created java object matching to payload with Builder pattern and then covert to Json using GsonBuilder like import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; public class JsonConvertor() { public static JsonObject convertToJsonObject(Object payload) { GsonBuilder builder = new GsonBuilder(); return (JsonObject) builder.setFieldNamingPolicy(FieldNamingPolicy.Policy). create().toJsonTree(payload); }}If I need to remove a required field I use, JsonObj.remove("key") on Json Object created by above function. 推荐答案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. 其他推荐答案import org.json.JSONObject // define/initialize jsonObj jsonObj.remove("field_key") |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |