在J#中将JSON反序列化为字符串数组或数据表

时间:2017-08-31 11:31:46

标签: c# asp.net json

string json = {"house":"#21-3-157/18, Sri Vaibhav","loc":"Subash nagar,Bolar","country":"India"}

反序列化时在数组

中提到json字符串时出错
  

无法反序列化当前的JSON对象(例如{" name":" value"})   到type' System.Collections.Generic.List,因为类型需要a   要正确反序列化的JSON数组(例如[1,2,3])。

我每次都失败了,尝试了很多不同的方法。请帮忙。

3 个答案:

答案 0 :(得分:1)

使用Json.NET

来自https://www.newtonsoft.com/json/help/html/QueryJsonDynamic.htm

的示例
string json = @"[
  {
    'Title': 'Json.NET is awesome!',
    'Author': {
      'Name': 'James Newton-King',
      'Twitter': '@JamesNK',
      'Picture': '/jamesnk.png'
    },
    'Date': '2013-01-23T19:30:00',
    'BodyHtml': '<h3>Title!</h3>\r\n<p>Content!</p>'
  }
]";

dynamic blogPosts = JArray.Parse(json);

dynamic blogPost = blogPosts[0];

string title = blogPost.Title;

Console.WriteLine(title);
// Json.NET is awesome!

string author = blogPost.Author.Name;

Console.WriteLine(author);
// James Newton-King

DateTime postDate = blogPost.Date;

Console.WriteLine(postDate);
// 23/01/2013 7:30:00 p.m.

另一个没有动态https://www.newtonsoft.com/json/help/html/QueryJson.htm

的示例

答案 1 :(得分:0)

您可以使用NewtonsoftJson库轻松解析json数据,而无需创建具体的类

using Newtonsoft.Json;

dynamic parse = Newtonsoft.Json.JsonConvert.DeserializeObject(json );
string house = parse.house.Value;
etc..

答案 2 :(得分:0)

您的JSON字符串不是转换为JSON字符串数组的格式。如果要将JSON字符串反序列化为List,那么您的格式应如下所示,

 string json = "[\"house\",\"loc\"]";

在您希望字符串Desrialize为数组时,您需要相应的实体,如下所示

public class Address
{
    public string House { get; set; }
    public string Loc { get; set; }
    public string Country { get; set; }
}

然后你应该反序列化到那个类型,

string json = "[{\"house\":\"#21-3-157/18,Sri Vaibhav\",\"loc\":\"Subash nagar,Bolar\",\"country\":\"India\"}]";
  List<Address> array = JsonConvert.DeserializeObject<List<Address>>(json);