[英]Modifying key values in a json array file, and writing the changed values to that same file
我在文件“ test.json”中有一個json數組。 該數組包含以下內容:
[
{
"txt": "this text is encrypted"
"ft": "this text is encrypted",
"Id": 2,
"No": 2,
},
{
"txt": "this text is encrypted"
"ft": "this text is encrypted",
"Id": 42,
"No": 2,
},
{
"txt": "this text is encrypted"
"ft": "this text is encrypted",
"Id": 12,
"No": 24,
},
.
.
.
. ~ 800 objects, each have the same signature
{
"txt": "this text is encrypted"
"ft": "this text is encrypted",
"Id": 47,
"No": 4,
}
]
任務
我想做的是,讀取test.json,分別遍歷數組中每個對象的每個鍵“ txt”和“ ft”(這些鍵的值已加密,我已經編寫了解密這些鍵的方法值),然后分別將這些值傳遞給我的crypto()方法,該方法分別返回解密的字符串,然后將test.json文件中每個密鑰的舊加密值覆蓋為數組中所有對象的新解密值。
我正在努力實現的目標
我在正確實現以下目標方面面臨困難:
我的嘗試
final String JSON_PATH = "/test.json";
BufferedReader br = new BufferedReader(new FileReader(JSON_PATH));
JsonParser parser = new JsonParser();
JsonArray arrayObj = parser.parse(br).getAsJsonArray();
for (JsonElement elm : arrayObj) {
JsonObject burObj = elm.getAsJsonObject();
String temp_fn ;
String temp_txt ;
String _fn = burObj.get("ft").getAsString();
String _txt = burObj.get("txt").getAsString();
temp_fn = Decrypt(_fn);
temp_txt= Decrypt(_txt);
}
這是在我的大腦停止工作之前所達到的程度,例如我如何將解密的字符串寫入適當的值鍵並覆蓋它們,同時保持test.json文件打開以使for循環可以通過數組中的下一個對象然后再次執行整個過程,直到完成為止。
對於5年內未用Java編寫的代碼質量,我也深表歉意!
將新的json對象重新保存到文件中。 還是這種方法對您不起作用?
如果所有對象都具有相同的簽名,請考慮創建一個包含以下字段的類:
public class Encrypted {
String txt;
String ft;
@SerializedName("Id")
int id;
@SerializedName("No")
int no;
}
然后按如下所示讀取您的JSON:
Collection<Encrypted> data = new Gson().fromJson(new JsonReader(new FileReader(filename)), new TypeToken<Collection<Encrypted>>(){}.getType());
遍歷對象,進行相應更改(解密)並保存
Collection<Encrypted> data;
再次使用JSON文件:
new Gson().toJson(data, new FileWriter(filename));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.