反序列化/将JSON转换为C#列表

时间:2018-06-22 11:26:53

标签: json .net-core json-deserialization

我有Web API,正在Dynamic中获取JSON对象,我需要转换为C#字符串,数组或列表,以便可以相应地提取数据。我尝试了多种选择,但没有得到任何结果。

我在var g1 = JsonConvert.DeserializeObject(item)处获得异常,下面粘贴了异常的副本

formStructureJsonBlob的第一个json对象是“ hiddenFields”,json输出粘贴在下面。

c#类

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

formStructureJsonBlob类型的output-json

{
    "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"
    }
 ]
}

错误

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

1 个答案:

答案 0 :(得分:1)

  1. 如果要遍历hiddenFields,则formStructureJsonBlob.hiddenFields应该可以在formStructureJsonBlob包含Json的情况下工作。检查示例
  2. 您不需要反序列化。只需访问如下所示的属性即可。

示例

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