我收到了来自Firebase的以下回复。我需要将自动生成的根节点复制为子节点。
const firebase = require('firebase-admin');
var serviceAccountSource = require("./source.json");
var serviceAccountDestination = require("./destination.json");
const sourceAdmin = firebase.initializeApp({
credential: firebase.credential.cert(serviceAccountSource),
databaseURL: "https://**********.firebaseio.com" // replace with source
});
const destinationAdmin = firebase.initializeApp({
credential: firebase.credential.cert(serviceAccountDestination),
databaseURL: "https://$$$$$.firebaseio.com"
}, "destination");
const collections = [ "books", "authors", ...]; // replace with your collections
var source = sourceAdmin.firestore();
var destination = destinationAdmin.firestore();
collections.forEach(colName => {
source.collection(colName).get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
destination.collection(colName).doc(doc.id).set({...doc.data()});
});
});
});
预期产量
{
"-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
}
}
我使用以下方法将FireBaseResponse字符串转换为上述模型
{
"-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
}
}
我该如何实现?
答案 0 :(得分:2)
您可以使用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);
答案 1 :(得分:1)
1)只需循环浏览您解析的JObject
的所有属性。
2)向子对象添加新属性,其值为AutoID
,其值为父名称。
3)然后将此子对象原样分配给JObject
中的父对象。
JObject jObject = JObject.Parse(firebaseResponse.Body);
foreach (var prop in jObject.Properties())
{
jObject[prop.Name] = JObject.FromObject(new
{
AutoId = prop.Name, //<= Child object name here
CustomerId = prop.Value["CustomerId"], //<= Remaining properties as it is
DateTime = prop.Value["DateTime"],
Id = prop.Value["Id"],
OrderId = prop.Value["OrderId"]
});
}
string outputJson = jObject.ToString();
输出:(来自调试器)