【发布时间】:2015-03-10 22:29:28
【问题描述】:
我正在使用 JSON,我将拥有这样的 JSON - 我将其称为 originalJsonResponse。下面所有的json都是一样的,只是user_id和uid字段可能有这些类型的变化-
{ "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_id 或 uid 字段(如果存在),如果这些字段的值不为空,则将这些字段的值更改为新的用户 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_id 和uid 字段的最佳方法是什么?
- 我可以在这里使用正则表达式来进行混淆吗?
- 我能想到的其他方法是使用 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_id 和 uid 字段,那么我应该能够轻松地做到这一点。
【问题讨论】: