Sres
Sres

Reputation: 21

Deserializing elastic search json data

I am trying to deserialize the JSON data of elastic search.I have created a json.txt file and copied the response of elastic search to that file. I can deserialize the array of JSON but it is difficult to deserialize all data. I have this class for JSON array.I am new to this stuffs so please help.

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; }
}

My main function is

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);

                  }

My JSON data is stored in a json.txt file.When I try to convert below data it works.

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


            }

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

But i cannot convert this json format.It throws an error for below 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"
            }
        }
    ]   
}

Upvotes: 0

Views: 1368

Answers (1)

Leonid
Leonid

Reputation: 1091

One of the ways to deserialize it to create addition objects:

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

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

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

Upvotes: 2

Related Questions