Json Deserialization to a class

谁说胖子不能爱 提交于 2019-12-11 04:52:50

问题


I have dynamic json result and i want to create an object for that json string. After that i will fill that object with the deserialized object. Here is the json string:

[{"_34":{
   "Id":"34",
   "Z":["42b23718-bbb8-416e-9241-538ff54c28c9","c25ef97a-89a5-4ed7-89c7-9c6a17c2413b"],
   "C":[]
   }
}]

How does the object look like? Or how can i deserialize this string to a class.

Thanks.


回答1:


You can use the JavaScriptSerializer which available out of the box or json.net if you prefer something open source.

Based on Darin Dimitrov's sample, here's how you'd do with json.net:

using System.Collections.Generic;
using System;
using Newtonsoft.Json;

namespace ConsoleApplication1
{
   class Program
   {
          static void Main(string[] args)
          {
              string json = "[{\"_34\":{ \"Id\":\"34\", \"Z\":[\"42b23718-bbb8-416e-9241-538ff54c28c9\",\"c25ef97a-89a5-4ed7-89c7-9c6a17c2413b\"], \"C\":[] } }]";
              var result = JsonConvert.DeserializeObject<Dictionary<string, Result>[]>(json);
              Console.WriteLine(result[0]["_34"].Z[1]);
           }
   }

   public class Result
   {
        public string Id { get; set; }
        public string[] Z { get; set; }
        public string[] C { get; set; }
   }
}



回答2:


Here's an example:

using System;
using System.Collections.Generic;
using System.IO;
using System.Web.Script.Serialization;

public class Result
{
    public string Id { get; set; }
    public string[] Z { get; set; }
    public string[] C { get; set; }
}

class Program
{
    static void Main()
    {
        var json = @"[{""_34"": {""Id"": ""34"",""Z"": [""42b23718-bbb8-416e-9241-538ff54c28c9"",""c25ef97a-89a5-4ed7-89c7-9c6a17c2413b""],""C"": []}}]";
        var serializer = new JavaScriptSerializer();
        var result = serializer.Deserialize<Dictionary<string, Result>[]>(json);
        Console.WriteLine(result[0]["_34"].Z[1]);
    }
}



回答3:


Target class

public class Target
{
    public string Id;
    public List<string> Z;
    public List<string> C;
}

Deserialization

var ser = new JavaScriptSerializer();
var obj = ser.Deserialize<Target>(json);



回答4:


Wrap your string in eval function:

var myObject = eval('(' + myJSONtext + ')');


来源:https://stackoverflow.com/questions/9394842/json-deserialization-to-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!