在网上找了好多几个处理的方法,也都没成功,索性找别人写的一个,(非常感谢他,虽然不知道他是谁,但把代码贴出来共享)下面我自己改了下!
import net.sf.json.JSONNull;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.Iterator;
public class TestJSON extends JsonUtil {
public static void main(String[] args) {
String str = "{body:{title:[{id:100,name:lisan,age:null,index:[{title:穿衣,age:null,zs:较冷}]},{id:1001,age:null,name:lisan1,index:[{title:穿衣1,age:null,zs:较冷1}]}]}}}";
JSONObject object = new JSONObject(str);
System.out.println(object);
JSONObject filterNull = filterNull(object);
System.out.println(filterNull);
}
/**
* 将json对象中包含的null和JSONNull属性修改成""
*
* @param jsonObj
*/
public static JSONObject filterNull(JSONObject jsonObj) {
Iterator it = jsonObj.keys();
Object obj = null;
String key = null;
while (it.hasNext()) {
key = it.next();
obj = jsonObj.get(key);
if (obj instanceof JSONObject) {
filterNull((JSONObject) obj);
}
if (obj instanceof JSONArray) {
JSONArray objArr = (JSONArray) obj;
for (int i = 0; i < objArr.length(); i++) {
filterNull(objArr.getJSONObject(i));
}
}
if (obj == null || obj instanceof JSONNull) {
jsonObj.put(key, "");
}
if (obj.equals(null)) {
jsonObj.put(key, "");
}
}
return jsonObj;
}
}
打印:
{"body":{"title":[{"name":"lisan","index":[{"zs":"较冷","title":"穿衣","age":null}],"id":100,"age":null},{"name":"lisan1","index":[{"zs":"较冷1","title":"穿衣1","age":null}],"id":1001,"age":null}]}}
{"body":{"title":[{"name":"lisan","index":[{"zs":"较冷","title":"穿衣","age":""}],"id":100,"age":""},{"name":"lisan1","index":[{"zs":"较冷1","title":"穿衣1","age":""}],"id":1001,"age":""}]}}