简体   繁体   English

用正则表达式替换字符串的一部分

[英]Replace part of the String by Regular Expression

My String input is something like: 我的字符串输入类似于:

{"key1":"value1","key2":"{\"key2_1\":\"123\",\"key2_2\":\"456\",\"key2_3\":\"33333\"}"}

The value fields in the above JSON could contain characters such as " , \\ and so on. For your convience here is the formatted version: 上面的JSON中的value字段可以包含诸如"\\等之类的字符。为了方便起见,这里是格式化后的版本:

{
    "key1": "value1",
    "key2": "{\"key2_1\":\"123\",\"key2_2\":\"456\",\"key2_3\":\"33333\"}"
}

I want to use Gson to convert the String into a Foo Object: 我想使用Gson将String转换为Foo对象:

class Foo {
    private String key1;
    private Bar key2;
    ...
}

class Bar {
    private String key2_1;
    private String key2_2;
    private String key2_3;
    ...
}

Here's my regular expression: 这是我的正则表达式:

String regexp = "\\{[\"a-zA-Z-0-9:,\\\\]*\"key2\":\"\\{\\\\\"key2_1\\\\\":\\\\\"[a-zA-Z0-9]*\\\\\",\\\\\"key2_2\\\\\":\\\\\"[a-zA-Z0-9]*\\\\\",\\\\\"key2_3\\\\\":\\\\\"[a-zA-Z0-9]*\\\\\"\\}\"\\}[\"a-zA-Z-0-9:,\\\\]*";
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(text);
if(matcher.matches()) {
    ... // TODO: Replace all "{, \" and }" but How???
}

How could I use this regular expression to replace all "{ , \\" .and "} into { , " , } without changing the keys and values in JSON? 如何在不更改JSON中的键和值的情况下使用此正则表达式将所有"{\\""} \\"替换为{"}

Finding the sub-string and using String's replace method will be my backup solution. 查找子字符串并使用String的replace方法将是我的备份解决方案。

Again, my ultimate goal is to parse the input String into my Foo object. 同样,我的最终目标是将输入的String解析为Foo对象。 Is there a better way rather than using regular expression? 有没有比使用正则表达式更好的方法?

Thank you! 谢谢!

The golden rule is DO NOT USE REGULAR EXPRESSIONS FOR SUCH THINGS :) My advice is too look to the JSON mappers, for example Jackson 黄金法则是: 不要在此类情况下使用常规表达式 :)我的建议也过于关注JSON映射器,例如Jackson

All you need to do: 您需要做的所有事情:

  1. Fix JSON in your example, here is no need double quotes around nested { 在您的示例中修复JSON,此处无需在嵌套{周围加上双引号
  2. Add Jackson dependencies 添加Jackson依赖

     <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> 
  3. Create ObjectMapper and let him handle your JSON string 创建ObjectMapper并让他处理您的JSON字符串

     ObjectMapper mapper = new ObjectMapper(); Foo foo = mapper.readValue( "{\\"key1\\":\\"value1\\",\\"key2\\":" + " {\\"key2_1\\":\\"123\\",\\"key2_2\\":\\"456\\",\\"key2_3\\":\\"33333\\"}}", Foo.class); System.out.println(foo.toString()); 

Hope it helps! 希望能帮助到你!

After digging further, I find those two links: 进一步挖掘之后,我发现了这两个链接:

Gson custom deseralizer for one variable in an object Gson自定义脱盐器,用于对象中的一个变量

Gson custom seralizer for one variable (of many) in an object using TypeAdapter 使用TypeAdapter为对象中的一个变量(多个变量)提供Gson自定义Seralizer

I achieved what I want by registering my own JsonDeserializer to GsonBuilder : 我通过向GsonBuilder注册自己的JsonDeserializer实现了我想要的:

private static GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapter(Bar.class, new JsonDeserializer<Bar>() {

    @Override
    public Bar deserialize(JsonElement json, Type typeOfT,
            JsonDeserializationContext context) throws JsonParseException {
        Bar result = new Bar();
        String regexp = "\"\\{\\\\\"key2_1\\\\\":\\\\\"(?s).*\\\\\".\\\\\"key2_2\\\\\":\\\\\"(?s).*\\\\\",\\\\\"key2_3\\\\\":\\\\\"(?s).*\\\\\"\\}\"";
        Pattern pattern = Pattern.compile(regexp);
        Matcher matcher = pattern.matcher(json.toString());
        String modifiedJsonStr = json.toString();
        if(matcher.matches()) {
            modifiedJsonStr = json.toString().replace("\"{", "{").replace("}\"", "}").replace("\\\"", "\"");
        }
        result = new Gson().fromJson(modifiedJsonStr, Bar.class);
        return result;
    }
});

Cheers. 干杯。

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

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