这是我的 Json 文件:
Here is my Json File:
{
"models":{},
"path":[
{
"path":"/web-profiles",
"operations":[
{
"type":"",
"responseMessages":[]
}
]
}
],
"produces":[]
}
如果键的值为空(包括 []、""、{}).如何从 Json 文件中删除这些对.
If the values of keys are empty (includes [], "", {}). How can I remove those pairs from Json file.
如果你使用javax.api API:
If you use javax.api API:
public static JsonArray removeNull(JsonArray array) {
JsonArrayBuilder builder = Json.createArrayBuilder();
int i = 0;
for (Iterator<JsonValue> it = array.iterator(); it.hasNext(); ++i) {
JsonValue value = it.next();
switch (value.getValueType()) {
case ARRAY:
JsonArray a = removeNull(array.getJsonArray(i));
if (!a.isEmpty())
builder.add(a);
break;
case OBJECT:
JsonObject object = removeNull(array.getJsonObject(i));
if (!object.isEmpty())
builder.add(object);
break;
case STRING:
String s = array.getString(i);
if (s != null && !s.isEmpty())
builder.add(s);
break;
case NUMBER:
builder.add(array.getJsonNumber(i));
break;
case TRUE:
case FALSE:
builder.add(array.getBoolean(i));
break;
case NULL:
break;
}
}
return builder.build();
}
public static JsonObject removeNull(JsonObject obj) {
JsonObjectBuilder builder = Json.createObjectBuilder();
for (Iterator<Entry<String, JsonValue>> it = obj.entrySet().iterator(); it.hasNext();) {
Entry<String, JsonValue> e = it.next();
String key = e.getKey();
JsonValue value = e.getValue();
switch (value.getValueType()) {
case ARRAY:
JsonArray array = removeNull(obj.getJsonArray(key));
if (!array.isEmpty())
builder.add(key, array);
break;
case OBJECT:
JsonObject object = removeNull(obj.getJsonObject(key));
if (!object.isEmpty())
builder.add(key, object);
break;
case STRING:
String s = obj.getString(key);
if (s != null && !s.isEmpty())
builder.add(key, s);
break;
case NUMBER:
builder.add(key, obj.getJsonNumber(key));
break;
case TRUE:
case FALSE:
builder.add(key, obj.getBoolean(key));
break;
case NULL:
break;
}
}
return builder.build();
}
@Test
public void testRemoveNullJsonObject() {
String str = ""
+ "{"
+ " "models":{},"
+ " "path":["
+ " {"
+ " "path":"/web-profiles","
+ " "operations":["
+ " {"
+ " "nickname":"CreateAWebExperienceProfile","
+ " "type":"","
+ " "responseMessages":[]"
+ " }"
+ " ]"
+ " }"
+ " ],"
+ " "produces":[]"
+ "}";
JsonObject json = Json.createReader(new StringReader(str)).readObject();
System.out.println(json);
JsonObject removed = removeNull(json);
System.out.println(removed);
// -> {"path":[{"path":"/web-profiles","operations":[{"nickname":"CreateAWebExperienceProfile"}]}]}
}
这篇关于JSONObject 删除空值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!