在我的项目客户端中,向我发送此JSON字符串。
{
"onlineRequest": {
"CustomerCode": "AB432A",
"MobileNumber": "75484568",
"ProductNo": "100",
"JsonFile": {
"evaluation": {
"number": [
{
"@para-id": "5656",
"@new-code": "",
"@text": "Hello America"
},
{
"@para-id": "3302",
"@new-code": "100",
"@text": "Hello Japan"
}
]
}
}
}
}
此JSON包含称为JsonFile
的内部JSON。现在,我需要按如下所示将此值设置为此JSON文件。
if @para-id = 5656, then @new-code = "0000"
if @para-id = 3302, then @new-code = "1111"
预期输出:
{
"onlineRequest": {
"CustomerCode": "AB432A",
"MobileNumber": "75484568",
"ProductNo": "100",
"JsonFile": {
"evaluation": {
"number": [
{
"@para-id": "5656",
"@new-code": "0000",
"@text": "Hello America"
},
{
"@para-id": "3302",
"@new-code": "1111",
"@text": "Hello Japan"
}
]
}
}
}
}
我该怎么做?
答案 0 :(得分:1)
可以通过Newtonsoft.Json
轻松完成:
var source = @"{
""onlineRequest"": {
""CustomerCode"": ""AB432A"",
""MobileNumber"": ""75484568"",
""ProductNo"": ""100"",
""JsonFile"": {
""evaluation"": {
""number"": [
{
""@para-id"": ""5656"",
""@new-code"": """",
""@text"": ""Hello America""
},
{
""@para-id"": ""3302"",
""@new-code"": ""100"",
""@text"": ""Hello Japan""
}
]
}
}
}
}";
var json = JToken.Parse(source);
var dict = new Dictionary<string, string>
{
["5656"] = "0000",
["3302"] = "1000",
};
foreach (var number in json.SelectToken("onlineRequest.JsonFile.evaluation.number").ToArray())
{
var id = (string)number["@para-id"];
if (id != null && dict.TryGetValue(id, out var code))
{
number["@new-code"] = code;
}
}