简体   繁体   English

编辑JSON字符串的最有效方法

[英]Most efficient way to edit JSON String

I have a JSON string that I can only access and not create. 我有一个只能访问但无法创建的JSON字符串。 Right now, the format of the JSON looks something like this: 现在,JSON的格式如下所示:

{ "ID": "1", "value": "{'ID': '1', 'more': {'Key': 'Value', 'Object': {'Akey': 'Avalue'}}}" }

I want to edit this JSON string to put into another function in a format similar to this: 我想编辑此JSON字符串以类似于以下格式放入另一个函数:

{ "ID": "1", "value": "{'ID': '1', 'Key': 'Value', 'Akey': 'Avalue'}" }

So basically, just remove the More and Object tags from the JSON string and the respective curly brackets. 因此,基本上,只需从JSON字符串和相应的大括号中删除More和Object标记即可。 One way this can be done is obviously just use splits and substrings in Java, however, is this the most efficient way? 可以做到的一种方法显然是在Java中仅使用split和substrings,但这是最有效的方法吗? If not, any other ideas on ways I can approach this? 如果没有,那么我有什么其他方法可以解决这个问题? I am using Java and the Apache Commons Sling JSON library (no options to change/add Java JSON libraries!) 我正在使用Java和Apache Commons Sling JSON库(没有更改/添加Java JSON库的选项!)

Thanks for your time! 谢谢你的时间!

您可以使用lib com.google.gson.Gson来管理json文件。

Unfortunately, native JSON support was delayed past Java 9 . 不幸的是,本地JSON支持被推迟到Java 9之后

Either substring & replace as you wrote, for more complicated situations, like removing the whole 'more' object, implement your own parser, for example: 对于更复杂的情况,例如删除整个“更多”对象,可以使用子字符串和替换操作,例如,实现自己的解析器:

    String value = "{'ID': '1', 'more': {'Key': 'Value', 'Object': {'Akey': 'Avalue'}}}";
    String delimiter = ", 'more'"; // pay attention to the comma, you can fix it by splitting by comma
    int start = value.indexOf(delimiter);
    System.out.println("start = " + start);
    Stack<Character> stack = new Stack<>();
    String substring = value.substring(start + delimiter.length(), value.length());
    System.out.println("substring = " + substring);
    char[] chars = substring.toCharArray();
    int end = 0;
    for (int i = 0; i < chars.length; i++) {
        char c = chars[i];
        if (c == '{')
            stack.push('{');
        if (c == '}') {
            stack.pop();
            if (stack.isEmpty()) {
                end = i;
                break;
            }
        }
    }
    System.out.println("end = " + end);
    String substring2 = value.substring(start, start + end + delimiter.length());
    System.out.println(substring2);
    System.out.println(value.replace(substring2, ""));

by counting parenthesis, output 通过计算括号,输出

start = 10
substring = : {'Key': 'Value', 'Object': {'Akey': 'Avalue'}}}
end = 47
, 'more': {'Key': 'Value', 'Object': {'Akey': 'Avalue'}
{'ID': '1'}}

Easy way: We can do it by substring or replace method of string. 简单方法:我们可以通过子字符串或替换字符串的方法来实现。 If need we can use regular expression for more accurate. 如果需要,我们可以使用正则表达式来更准确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM