更好的方法是在更深层次上删除json节点

时间:2017-08-14 06:37:40

标签: java json

下面是我的示例json文件,其中包含有关汽车的信息,我想删除" city"从下面的json数据中一次。 由于json数据包含太多的城市节点,我不想解析每个节点以删除" city"节点。我想删除" city" 节点以最简单的方式解析每个节点。我看着字符串替换为空,但它是大数据,在某些情况下可能会失败。

任何人都可以告诉我,什么是更好的方法来删除"城市"节点。

{
"carDetails":
[  
    {  
        "name":"John",
        "city":"Berlin",
        "cars":[  
            "audi",
            "bmw",
            "skoda": {
                "model": "f3z2",
                "manfactureDetails": {
                    "city": "vegas",
                    "time": "123967878734",
                    "color": "white",
                    "rawMaterial": {
                          "city": "london",
                          "quality": 1,
                          "importedDetails":{
                              "city" : "chile",
                              "date": "12/jan/2015",
                              ...........
                           }

                    }
                }
             }
        ],
        "job":"Teacher"
    },
    {  
        "name":"Mark",
        "city":"Oslo",
        "cars":[  
            "VW",
            "Toyata" {
               "manfactureDetails": {
                  "city" : "losangels",
                   .................
                           ..................
                }
            }

        ],
        "job":"Doctor"
    }
]
}

1 个答案:

答案 0 :(得分:0)

使用jsonia,您可以动态删除字段"":

public static void main(String[] args) {
    try (InputStream stream = new FileInputStream("test.json")) {
        try (OutputStream os = new FileOutputStream("output.json");
                Writer writer = new OutputStreamWriter(os, "UTF-8");
                PrintWriter out = new PrintWriter(writer)) {
            JSonHandler formatter = new JSonFormatter(out, true);
            ClassLoader cl = Thread.currentThread().getContextClassLoader();
            JSonHandler handler = (JSonHandler) Proxy.newProxyInstance(cl,
                    new Class<?>[] {JSonHandler.class},
                    new MyHandler(formatter));
            JSonParser.parse(stream, "UTF-8", handler);
        }
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}

MyHandler类看起来像这样:

private static class MyHandler implements InvocationHandler {
    private int level = 0;
    private final Object delegate;

    public MyHandler(Object delegate) {
        this.delegate = delegate;
    }

    @Override
    public Object invoke(Object proxy, Method method,
            Object[] args) throws Throwable {
        if (method.getName().equals("startField")
                && args[0].equals("city")) {
            ++level;
        } else if (method.getName().equals("endField")
                && args[0].equals("city")) {
            --level;
        } else if (level == 0) {
            return method.invoke(delegate, args);
        }
        return null;
    }
}