【问题标题】:Deserializing elastic search json data反序列化弹性搜索json数据
【发布时间】:2017-11-08 10:11:19
【问题描述】:

我正在尝试反序列化弹性搜索的 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"
            }
        }
    ]   
}

【问题讨论】:

  • 你没发现不一样吗?
  • 你必须根据json文件结构改变你的类结构。第一个 json 正确反序列化是因为您的 (C#) 类结构与您的 json 数据完全相同。
  • @RaviKumarGN 是的,我已经意识到了。谢谢

标签: c# .net json serialization


【解决方案1】:

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

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

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

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

【讨论】:

  • 非常感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-11-21
  • 2016-01-06
  • 2020-10-24
  • 2021-12-12
  • 1970-01-01
  • 2019-06-04
  • 2019-01-26
相关资源
最近更新 更多