【问题标题】:How to convert Firestore REST API response to normal json?如何将 Firestore REST API 响应转换为普通 json?
【发布时间】:2019-08-01 06:57:58
【问题描述】:

我正在尝试通过使用 Unity 的 REST API 来使用 Firestore。到目前为止,一切都按预期工作。

从 Firestore 读取文档时,它返回不同格式的 json。 像这样。

{
          "name": "projects/firestore-unity-demo-87998/databases/(default)/documents/test/panara",
          "fields": {
            "health": {
              "integerValue": "1008"
            },
            "name": {
              "stringValue": "Bhavin Panara"
            },
            "birthday": {
              "timestampValue": "1992-10-08T04:40:10Z"
            },
            "alive": {
              "booleanValue": true
            },
            "floatingPointNumber": {
              "testFloat": 100.1
            }
          },
          "createTime": "2019-07-30T13:27:09.599079Z",
          "updateTime": "2019-07-31T11:41:10.637712Z"
}

我怎样才能将这种json转换成这样的普通json。

{
  "health":1008,
  "name":"Bhavin Panara",
  "birthday" : "1992-10-08T04:40:10Z",
  "alive":true,
  "floatingPointNumber":100.1
}

【问题讨论】:

  • 你是如何查询数据库的?您能否提供更多代码,因为可能存在对象解析的替代方法
  • 你可以使用firestore-parser
  • 我希望在 Unity 中执行此操作。 firestore-parser 用于网络。不是吗?

标签: json firebase google-cloud-firestore json.net


【解决方案1】:

我使用了firestore-parser的代码


const getFireStoreProp = (value) => {
  const props = {
    arrayValue: 1,
    bytesValue: 1,
    booleanValue: 1,
    doubleValue: 1,
    geoPointValue: 1,
    integerValue: 1,
    mapValue: 1,
    nullValue: 1,
    referenceValue: 1,
    stringValue: 1,
    timestampValue: 1,
  };
  return Object.keys(value).find(k => props[k] === 1);
};

export const fireStoreParser = (value) => {
  let newVal = value;
  // You can use this part to avoid mutating original values
  //   let newVal;
  //   if (typeof value === 'object') {
  //     newVal = { ...value };
  //   } else if (value instanceof Array) {
  //     newVal = value.slice(0);
  //   } else {
  //     newVal = value;
  //   }
  const prop = getFireStoreProp(newVal);
  if (prop === 'doubleValue' || prop === 'integerValue') {
    newVal = Number(newVal[prop]);
  } else if (prop === 'arrayValue') {
    newVal = ((newVal[prop] && newVal[prop].values) || []).map(v => fireStoreParser(v));
  } else if (prop === 'mapValue') {
    newVal = fireStoreParser((newVal[prop] && newVal[prop].fields) || {});
  } else if (prop === 'geoPointValue') {
    newVal = { latitude: 0, longitude: 0, ...newVal[prop] };
  } else if (prop) {
    newVal = newVal[prop];
  } else if (typeof newVal === 'object') {
    Object.keys(newVal).forEach((k) => { newVal[k] = fireStoreParser(newVal[k]); });
  }
  return newVal;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-13
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-21
    • 2017-12-01
    • 2018-07-15
    相关资源
    最近更新 更多