c#将带有对象列表的json字符串转换为c#对象

时间:2018-03-26 19:08:58

标签: c# json

我要将字符串json转换为c#object,

我已经在这里读过几篇关于类似问题的回复,但没有一个解决方案有效。

这是json obj

concurrency

我根据json obj

创建了以下对象
{
   "Customer": {
     "data_0": {
        "id": "273714",
        "FirstName": "Zuzana",
        "LastName": "Martinkova"
     },
     "data_1": {
        "id": "274581",
        "FirstName": "Ricardo",
        "LastName": "Lambrechts"
     },
     "data_2": {
        "id": "275190",
        "FirstName": "Daniel",
        "LastName": "Mojapelo"
     },
     "data_3": {
        "id": "278031",
        "FirstName": "Sulochana",
        "LastName": "Chandran"
      }
   }
}

至于我的代码,我用一个我在这里找到的所有解决方案做了一个小的控制台应用程序示例

public class Customer
{
    public List<Data> Customers{ get; set; }
    public Customer()
    {
        Customers = new List<Data>();
    }
}
public class Data
{
    public string id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

我从第三方网络服务获得的json字符串所以仅仅是为了我从txt文件中读取json的例子,
读取后的jsonString参数值为:

static void Main(string[] args)
{
    try
    {
        string jsonString = File.ReadAllText(ConfigurationSettings.AppSettings["filepath"].ToString());

        //solution 1
        JObject jsonone = JObject.Parse(jsonString);
        var collection_one = jsonone.ToObject<Customer>();

        //solution 2
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        var collection_two = serializer.Deserialize<Customer>(jsonString);

        //solution 2
        var collection_three = JsonConvert.DeserializeObject<Customer> (jsonString);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message); ;
    }

    Console.ReadKey();
}

在我使集合计数为0的每个解决方案中,数据对象不包括在列表中。

有人能说些什么并告诉我出了什么问题吗? 提前致谢

2 个答案:

答案 0 :(得分:2)

您的JSON是Dictionary<string, Data>不是 a List<Data>。除此之外,您的财产被称为&#34;客户&#34;,&#34;客户&#34;。要解决这个问题,你需要改变一些事情:

public class Customer
{
    //JsonProperty is Used to serialize as a different property then your property name
    [JsonProperty(PropertyName = "Customer")] 
    public Dictionary<string, Data> CustomerDictionary { get; set; }
}
public class Data
{
    public string Id { get; set; } //You should make this "Id" not "id"
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

使用这些类定义,您可以轻松使用JsonConvert.DeserializeObject()JsonConvert.SerializeObject()方法:

Customer customer = JsonConvert.DeserializeObject<Customer>(json);
string newJson = JsonConvert.SerializeObject(customer);

我做了一个小提琴here来演示。

答案 1 :(得分:0)

你可以试试这个。

添加空类 public class Customer : Dictionary<string, Data>{} //empty class

并更新现有代码

//solution 1    
JObject jsonone = JObject.Parse(jsonString);

//Add this line
var token = jsonone.SelectToken("Customer").ToString();

//solution 2 - update jsonString to token variable created above.
var collection_three = JsonConvert.DeserializeObject<Customer>(token);