c# - 将 RootNode 复制到 JSON 中的 ChildNode

标签 c# json firebase-realtime-database

我从 firebase 收到了以下回复。我需要将自动生成的根节点复制为子节点。

{
"-LcjpjUB1ucnzDabnHa9": {
    "CustomerId": "9ff2a33e-815e-4d24-9985-2905c3460d8d",
    "DateTime": "4/18/2019 3:16:11 PM",
    "Id": "b59692a0-7fde-4132-aad7-d18a1aad690d",
    "OrderId": 11
},
"-Lcjs_DeDR8Q7kbuAdLo": {
    "CustomerId": "9ff2a33e-815e-4d24-9985-2905c3460d8d",
    "DateTime": "4/18/2019 3:28:33 PM",
    "Id": "be676d81-fa3f-4caa-8ea3-b921a705a09a",
    "OrderId": 12
}
}

预期输出

{
"-LcjpjUB1ucnzDabnHa9": {
    "AutoId":"-LcjpjUB1ucnzDabnHa9",
    "CustomerId": "9ff2a33e-815e-4d24-9985-2905c3460d8d",
    "DateTime": "4/18/2019 3:16:11 PM",
    "Id": "b59692a0-7fde-4132-aad7-d18a1aad690d",
    "OrderId": 11
},
"-Lcjs_DeDR8Q7kbuAdLo": {
    "AutoId":"-Lcjs_DeDR8Q7kbuAdLo",
    "CustomerId": "9ff2a33e-815e-4d24-9985-2905c3460d8d",
    "DateTime": "4/18/2019 3:28:33 PM",
    "Id": "be676d81-fa3f-4caa-8ea3-b921a705a09a",
    "OrderId": 12
}
}

我使用以下方法将 FireBaseResponse 字符串转换为上述模型 JObject json = JObject.Parse(firebaseResponse.Body);

我怎样才能实现这个目标?

最佳答案

您可以使用JObject的Add方法。遍历 json 属性并在每个节点中添加一个新属性:

var input = "{\r\n\"-LcjpjUB1ucnzDabnHa9\": {\r\n    \"CustomerId\": \"9ff2a33e-815e-4d24-9985-2905c3460d8d\",\r\n    \"DateTime\": \"4/18/2019 3:16:11 PM\",\r\n    \"Id\": \"b59692a0-7fde-4132-aad7-d18a1aad690d\",\r\n    \"OrderId\": 11\r\n},\r\n\"-Lcjs_DeDR8Q7kbuAdLo\": {\r\n    \"CustomerId\": \"9ff2a33e-815e-4d24-9985-2905c3460d8d\",\r\n    \"DateTime\": \"4/18/2019 3:28:33 PM\",\r\n    \"Id\": \"be676d81-fa3f-4caa-8ea3-b921a705a09a\",\r\n    \"OrderId\": 12\r\n}\r\n}";

var json = JObject.Parse(input);
foreach (var token in json)
{
    var jObject = (JObject) token.Value;
    jObject.Add("AutoId", new JValue(token.Key));
}

var result = json.ToString(Formatting.Indented);

关于c# - 将 RootNode 复制到 JSON 中的 ChildNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55743975/

相关文章:

ios - 完成的 Firebase 嵌套查询

javascript - Firechat - 无法发送消息

c# - 将 ToolStripMenu 重新用于 ToolStrip 或 ContextMenuStrip?

python - Instagram API : getting the user id of all the users who have liked a post

jquery - 错误/成功消息警报不会在第二次 ajax 调用中显示,而无需在 jquery 中再次刷新页面

PHP、MySQL、jQuery、AJAX : json data returns correct response but frontend returns error

java - Gradle 同步失败 : Plugin with id 'com.google.android.gms:play-services' not found

c# - 如何在Excel表格中创建表格?

c# - async wait 执行顺序错误

c# - 使用 Javascript 访问 GridViewRow 中的 Label 控件