反序列化弹性搜索json数据

时间:2017-11-08 10:11:19

标签: c# .net json serialization

我正在尝试反序列化弹性搜索的JSON数据。我创建了一个json.txt文件,并将弹性搜索的响应复制到该文件中。我可以反序列化JSON数组,但很难反序列化所有数据。 我有这个类用于JSON数组。我是这些东西的新手,所以请帮助。

public class tests
{
    public emp source { get; set; }

}
public class emp
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
    public string Salary { get; set; }
}

我的主要功能是

static void Main(string[] args)
    {

        var testdata = System.IO.File.ReadAllText(@"C:\Users\source\repos\JsonDeserialize\ConsoleApp2\jsondata.txt");  
           var test = JsonConvert.DeserializeObject<List<tests>>(testdata);
            var objemp = JsonConvert.DeserializeObject<List<emp>>(testdata);

                  }

我的JSON数据存储在json.txt文件中。当我尝试转换下面的数据时,它可以正常工作。

[
        {
            "source":
            {
                  "Id" : "1",
                  "Name" : "John",
                  "Department" : "IT",
                  "salary" : "45000"


            }

        },
        {
             "source":
             {"Id" : "1",
                  "Name" : "John123",
                  "Department" : "IT",
                  "salary" : "45000"
            }
        }
    ] 

但是我无法转换这个json格式。它会在json下面抛出一个错误。

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ConsoleApp2.hits]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

{
"_hits" :
    [
        {
            "source":
            {
                  "Id" : "1",
                  "Name" : "John",
                  "Department" : "IT",
                  "salary" : "45000"


            }

        },
        {
             "source":
             {"Id" : "1",
                  "Name" : "John123",
                  "Department" : "IT",
                  "salary" : "45000"
            }
        }
    ]   
}

1 个答案:

答案 0 :(得分:0)

将其反序列化以创建附加对象的方法之一:

public class ResultDocument
{
    public IEnumerable<ResultObject> _hits { get; set; }

}
public class ResultObject 
{
    public emp source { set;get; }
}

var objemp = JsonConvert.DeserializeObject<ResultDocument>(testdata);