多个嵌套的JSON信息-C#进程

多个嵌套的JSON信息-C#进程,c#,arrays,json,unity3d,C#,Arrays,Json,Unity3d,道歉如果我做错了什么,这是我的第一篇帖子 我目前正在使用C#,希望将一组数据保存到JSON文件并将其加载回,但我很难确定如何以以下格式获取它 // Primary ID 001 { // Secondary ID 01 { // Tertiary ID 01 { string: "this is some

道歉如果我做错了什么,这是我的第一篇帖子

我目前正在使用C#,希望将一组数据保存到JSON文件并将其加载回,但我很难确定如何以以下格式获取它

// Primary ID
    001
    {
         // Secondary ID
         01
         {
              // Tertiary ID
              01
              {
                   string: "this is some information.",
                   int: 9371
              }
         }

         // Secondary ID
         02
         {
              // Tertiary ID
              01
              {
                   string: "blah blah blah.",
                   int: 2241
              }
         }
    }
我基本上希望能够使用一组特定的ID调用信息,例如001-02-01,它将返回一个字符串(“诸如此类”)和一个int(2241)

我之所以想这样做,而不是仅仅拥有一个更长的ID,是因为当JSON文件变得非常大时,我希望能够通过依次传递每个ID来加快信息搜索

如果这是没有意义的,它将同样快,只是通过在一个更长的ID,而不是被这个完整的嵌套ID段的概念困扰,那么请让我知道


然而,如果我的想法是正确的,并且通过这样的结构来帮助查找特定数据的速度,我将如何进行呢?使用数组中的嵌套C#类?

最简单有效的方法是将所有数据都作为同一类型。目前,您似乎认为每个对象都属于给定id的类型:

{
   "01":{},
   "02" :{}
}
如果尝试使用可序列化的类,这将不会太好

我建议如下:

{
    "items" : [
       {"id":"01" }, { "id":"02" },...
    ]
}
然后,您可以使用

[Serializable]
public class Item
{
    public string id = null;
}
[Serializable]
public class RootObject
{
    public List<Item> items = null;
}

如果您最终在文件中存储了数百万条记录,并希望开始做一些性能更好的事情,那么切换到一个像样的文档数据库(如,而不是试图重新发明轮子)会更容易

在担心尚不存在的性能问题之前,先考虑编写好的标准代码

以下示例不是您选择的语言,但它确实解释了可以非常快速地搜索JSON和1000000个对象的数组:

const getIncidentId=()=>{
设id=Math.random().toString(36).substr(2,6).toUpperCase().replace(“O”,“0”)
返回`${id.slice(0,3)}-${id.slice(3)}`
}
console.log(“构建1000000个对象的数组”)
const littleData=Array.from({length:1000000},(v,k)=>k+1).map(x=>({cells:{Number:x,Id:getIncidentId()}))
log(“获取数组成员的随机ID列表[49,60,70000,700000,99999]”)
const randomIds=([49,60,700000,700000,999999]).map(i=>littleData[i].cells.Id)
console.log(随机ID)
log(“在随机Id列表中查找包含嵌套Id属性的每个数组项。”)
const foundItems=littleData.filter(i=>randomIds.includes(i.cells.Id))
console.log(foundItems)
void Start(){
    string str = GetJson(); // However you get it
    RootObject ro = JsonUtility.FromJson<RootObject>(str);
}
Dictionary<string, Item> dict = null;
void Start(){
    string str = GetJson(); // However you get it
    RootObject ro = JsonUtility.FromJson<RootObject>(str);
    this.dict = new Dictionary<string,Item>();
    foreach(Item item in ro.items){
        Item temp = temp;
        this.dict.Add(item.Id, temp);
    }
    ro = null;
}
Item GetItem(string id)
{
     if(string.IsNullOrEmpty(id) == true){ return null; }
     Item item = null;
     this.dict.TryGetValue(id, out item);
     return item;
}