将Json图转换为单个类对象

时间:2018-11-07 21:07:12

标签: c# .net json json.net

我使用C#和Json.NET,我想将带有数组的Json字符串转换为单个类对象。我尝试使用JsonConvert.Populate和JsonProperty DataAnnotation,但是没有用

这是我尝试过的一个例子

JSON字符串:

{  
   "name":"julian",
   "card":{  
      "cardholder":{  
         "identification":{  
            "number":"32556188",
            "type":"DNI"
         },
         "name":"John"
      }
   }
}

C#类:

public class Payment
{
    [JsonProperty("name")]
    public string Name { get; set; }

    [JsonProperty("card.cardholder.name")]
    public string CardHolderName { get; set; }

    [JsonProperty("card.cardholder.identification.number")]
    public string CardHolderIdentificationNumber { get; set; }
}

转换代码:

var jsonString = ObtainJSONString();
var _payment = new Payment();
JsonConvert.PopulateObject(jsonString, _payment);

2 个答案:

答案 0 :(得分:1)

假设使用以下模型:

public class Payment
{
    public string Name { get; set; }
    public string CardHolderName { get; set; }
    public string CardHolderIdentificationNumber { get; set; }
}

您可以像这样解析json字符串:

string json = @"{  
   ""name"":""julian"",
   ""card"":{  
      ""cardholder"":{  
         ""identification"":{  
            ""number"":""32556188"",
            ""type"":""DNI""
         },
         ""name"":""John""
      }
   }
}";

var token = JObject.Parse(json);

var payment = new Payment
{
    Name = token["name"].ToString(),
    CardHolderName = token["card"]["cardholder"]["name"].ToString(),
    CardHolderIdentificationNumber = token["card"]["cardholder"]["identification"]["number"].ToString()
};

答案 1 :(得分:0)

您需要的是反序列化,而我个人使用的是Newtonsoft Json,那么您可以使用以下语法:

var paymentObject = JsonConvert.DeserializeObject<Payment>(jsonString );

https://www.newtonsoft.com/json/help/html/DeserializeObject.htm