【问题标题】:How to create a new JSON string by modifying few fields in it using Regular Expressions?如何通过使用正则表达式修改其中的几个字段来创建新的 JSON 字符串?
【发布时间】:2015-03-10 22:29:28
【问题描述】:

我正在使用 JSON,我将拥有这样的 JSON - 我将其称为 originalJsonResponse。下面所有的json都是一样的,只是user_iduid字段可能有这些类型的变化-

{ "user_id": { "long": 159002376 }, "filter": { "string": "hello" } }
{ "user_id": { "string": "159002376" }, "filter": { "string": "hello" } }
{ "user_id": "159002376" , "filter": { "string": "hello" } }
{ "user_id": 159002376 , "filter": { "string": "hello" } }
{ "user_id": null, "filter": { "string": "hello" } }

{ "uid": { "long": 159002376 }, "filter": { "string": "hello" } }
{ "uid": { "string": "159002376" }, "filter": { "string": "hello" } }
{ "uid": "159002376" , "filter": { "string": "hello" } }
{ "uid": 159002376 , "filter": { "string": "hello" } }
{ "uid": null, "filter": { "string": "hello" } }

{ "filter": { "string": "hello" } }

现在我需要从 JSON 中提取 user_iduid 字段(如果存在),如果这些字段的值不为空,则将这些字段的值更改为新的用户 ID,然后构造另一个包含新用户 ID 的新 json。

例如,我将newUserId 设置为1267818821,那么我的新json 应该是这样的,并且新json 应该与旧json 具有相同的结构-

{ "user_id": { "long": 1267818821 }, "filter": { "string": "hello" } }
{ "user_id": { "string": "1267818821" }, "filter": { "string": "hello" } }
{ "user_id": "1267818821" , "filter": { "string": "hello" } }
{ "user_id": 1267818821 , "filter": { "string": "hello" } }
{ "user_id": null, "filter": { "string": "hello" } }

{ "uid": { "long": 1267818821 }, "filter": { "string": "hello" } }
{ "uid": { "string": "1267818821" }, "filter": { "string": "hello" } }
{ "uid": "1267818821" , "filter": { "string": "hello" } }
{ "uid": 1267818821 , "filter": { "string": "hello" } }
{ "uid": null, "filter": { "string": "hello" } }

{ "filter": { "string": "hello" } }

混淆user_iduid 字段的最佳方法是什么?

  • 我可以在这里使用正则表达式来进行混淆吗?
  • 我能想到的其他方法是使用 Gson 解析 JSON,但如果我走这条路,那么 GSON 将所有内容都读取为 Double,我的值可能会在读取时发生变化。

以下是我想要进行混淆的方法 -

private static String obfuscateJson(String originalJsonResponse, String oldUserId, String newUserId) {
    // here oldUserId is 159002376 and newUserId is 1267818821

    // not sure what I should do here to construct a new json with newUserId

    String newJsonResponse = // make a new json here
    return newJsonResponse;
}

我不能在这里使用replaceAll 方法(这就是我开始使用的方法并意识到它不起作用)因为我可能有另一个具有不同字段的json,并且这些字段中可能有oldUserId 数字所以我不想替换那些。有没有更好的方法呢?

// not a good solution
String newJsonResponse = originalJsonResponse.replaceAll(String.valueOf(oldUserId), String.valueOf(newUserId));

我想让这个更通用,以便将来如果我想替换一些其他字段而不是 user_iduid 字段,那么我应该能够轻松地做到这一点。

【问题讨论】:

    标签: java regex json


    【解决方案1】:

    由于您已在此处分享了 user_id 字段的所有可能输入 JSON 字符串模式,我想再次展示我的 JSON 解析器解决方案,建议 before,但现在已更新以处理您的不同 JSON 类型。

    public static void main(String[] args) {
        String[][] jsonInputs = new String[6][2];
    
        jsonInputs[0][0] = "Long-Object";
        jsonInputs[0][1] = "{ \"user_id\":{\"long\":876},\"client_id\":{\"int\":0},\"affinity\":[{\"try\":{\"long\":55787693},\"scoring\":{\"float\":0.19}},{\"try\":{\"long\":1763},\"scoring\":{\"float\":0.0114}}]}";
    
        jsonInputs[1][0] = "String-Object";
        jsonInputs[1][1] = "{ \"user_id\":{\"string\": \"876\"},\"client_id\":{\"int\":0},\"affinity\":[{\"try\":{\"long\":55787693},\"scoring\":{\"float\":0.19}},{\"try\":{\"long\":1763},\"scoring\":{\"float\":0.0114}}]}";
    
        jsonInputs[2][0] = "String";
        jsonInputs[2][1] = "{ \"user_id\": \"1267818821\" , \"filter\": { \"string\": \"hello\" } }";
    
        jsonInputs[3][0] = "Long";
        jsonInputs[3][1] = "{ \"user_id\": 1267818821 , \"filter\": { \"string\": \"hello\" } }";
    
        jsonInputs[4][0] = "Null";
        jsonInputs[4][1] = "{ \"user_id\": null , \"filter\": { \"string\": \"hello\" } }";
    
        jsonInputs[5][0] = "Not-Present";
        jsonInputs[5][1] = "{ \"filter\": { \"string\": \"hello\" } }";
    
        for (String[] json : jsonInputs) {
            System.out.println(json[0]);
            System.out.println(changeJsonString(json[1], "54321"));
            System.out.println();
        }
    }
    
    private static String changeJsonString(String originalResponse, String newId) {
        try {
            JSONObject root = new JSONObject(originalResponse);
            if (!root.isNull("user_id")) {
                Object userObj = root.get("user_id");
                if (userObj instanceof JSONObject) {
                    JSONObject userId = (JSONObject) userObj;
                    if (userId.has("long")) {
                        userId.put("long", Long.parseLong(newId));
                    } else {
                        userId.put("string", newId);
                    }
                } else if (userObj instanceof Number) {
                    root.put("user_id", Long.parseLong(newId));
                } else {
                    root.put("user_id", newId);
                }
            }
            return root.toString();
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    }
    

    输出:

    Long-Object
    {"user_id":{"long":54321},"client_id":{"int":0},"affinity":[{"scoring":{"float":0.19},"try":{"long":55787693}},{"scoring":{"float":0.0114},"try":{"long":1763}}]}
    
    String-Object
    {"user_id":{"string":"54321"},"client_id":{"int":0},"affinity":[{"scoring":{"float":0.19},"try":{"long":55787693}},{"scoring":{"float":0.0114},"try":{"long":1763}}]}
    
    String
    {"filter":{"string":"hello"},"user_id":"54321"}
    
    Long
    {"filter":{"string":"hello"},"user_id":54321}
    
    Null
    {"filter":{"string":"hello"},"user_id":null}
    
    Not-Present
    {"filter":{"string":"hello"}}
    

    【讨论】:

      【解决方案2】:

      不是适合正则表达式的用例。

      对于这种类型的东西,JSON 处理器 绝对是您想要使用的。通过这种方式,您可以将传入的 JSON 反序列化到您定义的类中,根据需要更改值和结构,然后将其序列化回传出 JSON 响应。

      我使用并且会推荐Jackson,但如果您愿意,也可以使用 GSON。还有一个 Jackson quickstart tutorial

      您可以指定注释@JsonInclude(Include.NON_NULL) 仅序列化非空值,这样如果JSONuser_id 但没有uid,则null uid 不会被序列化。

      要处理特定属性中不同变体的复杂性(例如,user_id 作为longstring 或任一类型的嵌套哈希),最好编写custom serializers 和解串器。 GSON 也有这些。

      【讨论】:

        猜你喜欢
        • 2015-03-01
        • 2016-05-04
        • 2018-09-14
        • 2014-01-29
        • 2020-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多