Java-在没有POJO的情况下递归地从JSON字符串中删除字段

时间:2018-11-09 11:59:38

标签: java json jackson gson

如何从JSON字符串中递归删除某些具有指定名称的字段?

例如,我想从以下JSON中删除字段“ secondName”:

输入:

{
    "name" : "abc",
    "secondName": "qwe",
    "add" : "abcd",
    "moreDetails" : {
        "secondName": "qwe",
        "age" : "099"
    }
}

输出:

{
    "name" : "abc",
    "add" : "abcd",
    "moreDetails" : {
        "age" : "099"
    }
}

我必须从具有不同结构/架构的许多不同JSON中删除某些字段,因此无法对POJO反序列化/序列化。

3 个答案:

答案 0 :(得分:1)

您可以尝试将JSON存储为JSONObject,使用jsonObject.names()遍历密钥,并使用jsonObject.remove(key)删除条目。

答案 1 :(得分:1)

如果您知道架构和层次结构,则可以执行以下操作:

timeLeftShapeLayer.strokeEnd += 0.1

请参阅此以获取更多信息Remove key from a Json inside a JsonObject

否则,您需要编写一个动态函数,该函数将检查JSON对象的每个元素,并尝试在其中找到class ViewController: UIViewController { let timeLeftShapeLayer = CAShapeLayer() let bgShapeLayer = CAShapeLayer() override func viewDidLoad() { super.viewDidLoad() drawBgShape() drawTimeLeftShape() } func drawBgShape() { bgShapeLayer.path = UIBezierPath( arcCenter: CGPoint(x: view.frame.midX , y: view.frame.midY), radius: 100, startAngle: -90.degreesToRadians, endAngle: 270.degreesToRadians, clockwise: true ).cgPath bgShapeLayer.strokeColor = UIColor.lightGray.cgColor bgShapeLayer.fillColor = UIColor.clear.cgColor bgShapeLayer.lineWidth = 15 view.layer.addSublayer(bgShapeLayer) } func drawTimeLeftShape() { timeLeftShapeLayer.path = UIBezierPath( arcCenter: CGPoint(x: view.frame.midX , y: view.frame.midY), radius: 100, startAngle: -90.degreesToRadians, endAngle: 270.degreesToRadians, clockwise: true ).cgPath timeLeftShapeLayer.strokeColor = UIColor.red.cgColor timeLeftShapeLayer.fillColor = UIColor.clear.cgColor timeLeftShapeLayer.lineWidth = 15 timeLeftShapeLayer.strokeEnd = 0.0 view.layer.addSublayer(timeLeftShapeLayer) } @IBAction func click(_ sender: Any) { timeLeftShapeLayer.strokeEnd += 0.1 } } 元素并将其删除。

因此在这里考虑一下,因为您有多个嵌套对象,那么您需要编写一个函数,该函数将遍历每个元素并检查其类型(如果它再次通过jsonObject递归或迭代地调用同一方法以检查当前元素),请在每次检查中进行检查您还需要验证密钥,如果它与必须删除的密钥匹配,则可以将其删除并继续操作。

有关如何检查JSON值类型的提示,请参见此How to check the type of a value from a JSONObject?

答案 2 :(得分:0)

Gson将任何有效的Json反序列化为LinkedTreeMap,例如:

LinkedTreeMap<?,?> ltm = new Gson().fromJson(YOUR_JSON, LinkedTreeMap.class);

然后就是要做一些递归方法来进行清理:

public void alterEntry(Entry<?, ?> e) {
    if(e.getValue() instanceof Map) {
        alterMap((Map<?, ?>) e.getValue());
    } else {
        if(e.getKey().equals("secondName")) { // hard coded but you see the point 
            e.setValue(null); // we could remove the whole entry from the map
                              // but it makes thing more complicated. Setting null
                              // achieves the same.
        }
    }
}

public void alterMap(Map<?,?> map) {
    map.entrySet().forEach(this::alterEntry);
}

用法:

alterMap(ltm);