Gabriel Sule
Gabriel Sule

Reputation: 383

How to deserialize Json file in c # to insert in table

I have the following json and I am trying to deserialize to insert it into a SQL table, I have tried to use JsonConvert and JObject without positive result

Json

{
"id": "123123",
"publisherId": "Empresa",
"notificationType": "Orden",
"headers": {
    "providerId": "ABC123"
},
"content": {
    "id": "987987",
    "orderId": "4444444",
    "apiName": "Services",
    "method": "GetOrder",
    "verb": "GET",
    "urlMethod": "https://api.com"
},
"contentVersion": "1.0"
}

Model

    public class Headers
    {
        public string providerId { get; set; }
    }

    public class Content
    {
        public string id { get; set; }
        public string orderId { get; set; }
        public string apiName { get; set; }
        public string method { get; set; }
        public string verb { get; set; }
        public string urlMethod { get; set; }
    }

    public class RootModel
    {
        public string id { get; set; }
        public string publisherId { get; set; }
        public string notificationType { get; set; }
        public Headers headers { get; set; }
        public Content content { get; set; }
        public string contentVersion { get; set; }
    }

Code

    public static List<Models.RootModel> getJson()
    {
        using (StreamReader r = new StreamReader("c:\\LOG\\20180528\\201805281039.json"))
        {
            string json = r.ReadToEnd();
            return JsonConvert.DeserializeObject<Models.RootModel>(json);
        }
    }

You are giving me the following error

Error CS0029 No se puede convertir implícitamente el tipo 'WebApplication1.Models.RootModel' en 'System.Collections.Generic.List'

I really do not know if I'm on the right track, is it necessary to deserialize to insert in the DB, or is there another way?

Thanks in advance for the help

Upvotes: 2

Views: 574

Answers (2)

AneeshPutturi
AneeshPutturi

Reputation: 768

change your code

public static Models.RootModel getJson()
    {
        using (StreamReader r = new StreamReader("c:\\LOG\\20180528\\201805281039.json"))
        {
            string json = r.ReadToEnd();
            return JsonConvert.DeserializeObject<Models.RootModel>(json);
        }
    }

Upvotes: 1

David
David

Reputation: 219037

Just as the error states, it can not implicitly convert an instance of your model to a collection of your model.

You're trying to return a single instance:

return JsonConvert.DeserializeObject<Models.RootModel>(json);

But your method is expecting to return a list of instances:

public static List<Models.RootModel> getJson()

If you're just returning one instance (since the JSON represents an object, not an array of objects), change your method to reflect that:

public static Models.RootModel getJson()

Upvotes: 2

Related Questions