K.Z
K.Z

Reputation: 5075

Deserialize/ convert JSON to C# list

I have Web API where I am getting JSON object in Dynamic and I need to convert to C# string, array or list so that I can pull data accordingly. I have tried multiple option but not getting any result.

I get exception at var g1 = JsonConvert.DeserializeObject(item), copy of exception pasted below

formStructureJsonBlob first json object is 'hiddenFields', json output pasted below.

c# class

public dynamic formStructureJsonBlob { get; set; }


    public override Guid Execute()
    {
        try
        {
            foreach (var item in formStructureJsonBlob)
            {
                var g1 = JsonConvert.DeserializeObject(item); // getting error here 
            }

            //JObject j = new JObject();
            // JToken jt = j.SelectToken(formStructureJsonBlob.hiddenFields[0].name);
        }
        catch(Exception e)
        {
            Console.WriteLine(e);
        }

output-json of formStructureJsonBlob type

{
    "hiddenFields": [{
        "order": 0,
        "type": "hidden",
        "name": "formId",
        "value": "v1"
    },
    {
        "order": 0,
        "type": "hidden",
        "name": "consultationId",
        "value": "v2"
    },
    {
        "order": 0,
        "type": "hidden",
        "name": "clientId",
        "value": "v3"
    }
 ]
}

error

{Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: The best overloaded 
method match for 'Newtonsoft.Json.JsonConvert.DeserializeObject(string)' has 
some invalid arguments
 at CallSite.Target(Closure , CallSite , Type , Object )
 at Ant.Analysis.Infrastructure.Commands.SaveFormQuestionsAnswers.Execute() 
in C:\Developments\SaveFormQuestionsAnswers.cs:line 34}

Upvotes: 0

Views: 372

Answers (1)

Raxit
Raxit

Reputation: 111

  1. If you want to iterate over hiddenFields then formStructureJsonBlob.hiddenFields should work ssuming formStructureJsonBlob holds Json. check example
  2. You do not need to Deserialize. Just access the properties as shown below.

Example,

public dynamic formStructureJsonBlob { get; set; }


public override Guid Execute()
{
    try
    {
        foreach (var item in formStructureJsonBlob.hiddenFields)
        {
Console.Write(item.order);
Console.Write(item.type);
Console.Write(item.name);
Console.Write(item.value); 
        }

    }
    catch(Exception e)
    {
        Console.WriteLine(e);
    }
}

Upvotes: 1

Related Questions