C# Json To对象字典

oknwwptz  于 2023-03-24  发布在  C#
关注(0)|答案(4)|浏览(142)

我想取一些Json并将其解析为键/值对的集合,但有些值本身就是字典。我尝试了通常的Newtonsoft反序列化。它很接近,但不完全正确。最终结果必须是字典,而不是强类型类。
这是一个Json的例子:

{
  "JobNumber": 1010,
  "Asset": null,
  "JobNotes": [
    {
      "NoteText": "It's not working.",
      "NoteType": "Complaint"
    },
    {
      "NoteText": "Needs to be fixed",
      "NoteType": "Job"
    }
  ]
}

这是我用来反序列化的代码:

var json = File.ReadAllText(@"c:\temp\job.json");
        var result = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);

结果几乎是正确的,但键为“JobNotes”的项的值只是json string。我希望解析器递归并将内部Json反序列化到字符串和对象的进一步字典中。有没有方法可以用Newtonsoft库做到这一点?或者,是否有其他的库可以完成这个任务?我是否可以挂钩到解析方法来覆盖那个时间点的功能?

sqxo8psd

sqxo8psd1#

这是@DanielKeogh的代码的修改版本,运行良好。

class Program
{
    static void Main(string[] args)
    {
        var json = File.ReadAllText(@"c:\temp\job3.json");
        var result = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
        RecurseDeserialize(result);
    }

    private static void RecurseDeserialize(Dictionary<string, object> result)
    {
        //Iterate throgh key/value pairs
        foreach (var keyValuePair in result.ToArray())
        {
            //Check to see if Newtonsoft thinks this is a JArray
            var jarray = keyValuePair.Value as JArray;

            if (jarray != null)
            {
                //We have a JArray

                //Convert JArray back to json and deserialize to a list of dictionaries
                var dictionaries = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(jarray.ToString()); 

                //Set the result as the dictionary
                result[keyValuePair.Key] = dictionaries;

                //Iterate throught the dictionaries
                foreach (var dictionary in dictionaries)
                {
                    //Recurse
                    RecurseDeserialize(dictionary);
                }
            }
        }
    }
}

这个修改后的Json显示了它的深度:

{
  "JobNumber": 1010,
  "Asset": null,
  "JobNotes": [
    {
      "NoteText": "It's not working.",
      "NoteType": "Complaint"
    },
    {
      "NoteText": "Needs to be fixed",
      "NoteType": "Job",
      "JobNoteNotes": [
        {
          "Something": 1,
          "Something2": "Test"
        }
      ]
    }
  ]
}

结果结束三个字典深度,以便我可以通过键获得“Something”值。

vfwfrxfs

vfwfrxfs2#

这可以通过一点递归来完成。我将把定义IsJson留给你作为学术练习。:)

Dictionary<string, object> RecursiveDeserialize(string json)
{
     var result = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
     foreach (var pair in result.ToArray())
     {
         if(IsJson(pair.Value))
         {
             result[pair.Key] = RecursiveDeserialize(pair.Value);
         }
     }
     return result;
}
vybvopom

vybvopom3#

将此对象用于json字符串

public class JobNote
{
    public string NoteText { get; set; }
    public string NoteType { get; set; }
}

public class ListJob
{
    public int JobNumber { get; set; }
    public object Asset { get; set; }
    public List<JobNote> JobNotes { get; set; }
}

然后可以反序列化它

hwamh0ep

hwamh0ep4#

修改了@ christian-findlay的答案,在迭代时也将JObject类型转换为Dictionary〈string,object〉:

private static void RecurseDeserialize(Dictionary<string, object> result)
    {
        foreach (var keyValuePair in result.ToArray())
        {
            var jarray = keyValuePair.Value as JArray;

            if (jarray != null)
            {
                var dictionaries = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(jarray.ToString());
                result[keyValuePair.Key] = dictionaries;

                foreach (var dictionary in dictionaries)
                {
                    RecurseDeserialize(dictionary);
                }
            }
            else 
            {
                var jobject = keyValuePair.Value as JObject;
                if (jobject != null)
                {
                    var dictionary = JsonConvert.DeserializeObject<Dictionary<string, object>>(jobject.ToString());
                    result[keyValuePair.Key] = dictionary;
                    RecurseDeserialize(dictionary);
                }
            }
        }
    }

相关问题