使用逗号分隔值反序列化JSON

6yjfywim  于 2023-03-20  发布在  其他
关注(0)|答案(3)|浏览(126)

我想反序列化一个JSON,其中一个节点包含逗号分隔的值。但是包含逗号的对象在反序列化时返回null。
输入JSON:

{
  "SolutionTabletSubSectionUId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "SolutionTabletSubSectionId": 1,
  "SolutionTabletUId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "Title": "string",
  "SubTitle": "string",
  "Description": "string",
  "Link": "www.google.com,www.facebook.com",
  "LinkDisplayName": "DisplayName1,DisplayName2",
  "SolutionTabletConfigurationUId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "SolutionTabletTemplateUId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "ImageName": "string",
  "ImagePath": "string",
  "DisplayOrderId": 0,
  "TemplateComponentUId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
  "FooterTitle": "string",
  "FooterDescription": "string"
}

代码:

var list = new List<MyList>();
list.Add(JsonConvert.DeserializeObject<MyClass>(input));
MySubClass resultSet = new MySubClass();
resultSet.Data = list;

我的课程:

public class MyClass
{
    public Guid SolutionTabletSubSectionUId { get; set; }
    public int SolutionTabletSubSectionId { get; set; }
    public string LinkDisplayName { get; set; }
    public string Link { get; set; }
    public List<LinkNamesNode> LinkNames { get; set; }
}

public class LinkNamesNode
{
    public string LinkDisplayName { get; set; }
    public string Link { get; set; }
}

调试时,我发现LinkNames设置为null或未命中,因为未找到属性名称。请帮助我反序列化对象。
我的输出应如下所示:

{
  "LoggedInUser": "string",
  "Data": [
    {
      "SolutionTabletSubSectionUId": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
      "SolutionTabletSubSectionId": 0
      "LinkNames": [
        {
          "LinkDisplayName": "DisplayName1",
          "Link": "www.google.com"
        },
        {
          "LinkDisplayName": "DisplayName2",
          "Link": "www.facebook.com"
        }
      ]
  ]
}

请协助。

rkkpypqq

rkkpypqq1#

您可以使用JsonConstructorAttribute来实现自定义反序列化逻辑。
由于提到了LinkLinkDisplayName的大小在被分隔符拆分后可能在长度上不同:
1.获取linkslinkDisplayNames数组之间的最大值。
1.使用Array.ElementAtOrDefault(i)方法,通过index安全地从数组中获取值,并将对象添加到LinkNames数组中。

public class MyClass
{
    [JsonConstructor]
    public MyClass(Guid solutionTabletSubSectionUId, int solutionTabletSubSectionId, string linkDisplayName, string link)
    {
        SolutionTabletSubSectionUId = solutionTabletSubSectionUId;
        SolutionTabletSubSectionId = solutionTabletSubSectionId;
        LinkDisplayName = linkDisplayName;
        Link = link;
        LinkNames = new List<LinkNamesNode>();
        
        string[] links = new string[] {};
        if (!String.IsNullOrWhiteSpace(link))
            links = link.Split(',').ToArray();
        
        string[] linkDisplayNames = new string[] {};
        if (!String.IsNullOrWhiteSpace(linkDisplayName))
            linkDisplayNames = linkDisplayName.Split(',').ToArray();
        
        for (int i = 0; i < Math.Max(links.Length, linkDisplayNames.Length); i++)
        {
            LinkNames.Add(new LinkNamesNode
                          {
                              Link = links.ElementAtOrDefault(i),
                              LinkDisplayName = linkDisplayNames.ElementAtOrDefault(i)
                          });
        }
    }
    
    public Guid SolutionTabletSubSectionUId { get; set; }

    public int SolutionTabletSubSectionId { get; set; }

    public string LinkDisplayName { get; set; }

    public string Link { get; set; }

    public List<LinkNamesNode> LinkNames { get; set; }
}
yhived7q

yhived7q2#

你可以用一个中间物体来解决这个问题,因为两边的结构是不一样的。
1.创建一个临时类:
公共类MyTempClass {公共GUID解决方案表子部分UId { get;set; }公共整数解决方案表子部分ID { get;设置; }

public string Link;

    public string LinkDisplayName;

    public  MyClass ConverToMyClass()
    {
        MyClass c = new MyClass();
        c.LinkNames = new List<LinkNamesNode>();
        c.SolutionTabletSubSectionId = this.SolutionTabletSubSectionId;
        c.SolutionTabletSubSectionUId = this.SolutionTabletSubSectionUId;
        List<string> links = this.Link.Split(",").ToList();
        List<string> linkNames = this.LinkDisplayName.Split(",").ToList();
        for (int i = 0; i < links.Count; i++)
        {
            c.LinkNames.Add(new LinkNamesNode()
            { Link = links[i], LinkDisplayName = linkNames[i] });
        }

        return c;
    }
}

1.将代码更改为:
字符串输入=文件.读取所有文本(“C:\工作目录\堆栈溢出\json序列化\控制台应用1\控制台应用1\jsconfig 1. json”);我的临时类结果= JsonConvert.反序列化对象(输入);转换为我的类();
希望这个有用。

k3fezbri

k3fezbri3#

您可以创建一个JSON转换器

var result = JsonConvert.DeserializeObject<MyClass>(json, new StringConverter());

public class StringConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var jObj = JObject.Load(reader);
        var l = ((string)jObj["Link"]).Split(",");

        var result = jObj.ToObject<MyClass>();
        result.LinkNames = ((string)jObj["LinkDisplayName"]).Split(",")
                            .Zip(l, (k, v) => new LinkNamesNode { LinkDisplayName = k, Link = v })
                            .ToList();
        return result;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(MyClass);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

并从类中删除这些属性,则您不再需要它们

public string LinkDisplayName { get; set; }
    public string Link { get; set; }

相关问题