jsonconvert.deserializeObject,所有对象



我无法打印p.paperp.penp.eraserp.box。原因:

1.也许类rootobject是错误的定义,如何修复?

2. JSON输入可能是更改1 row, 3 row或超过2163行,我该如何处理所有情况?我不仅要从1行,而且还要从2163行获取数据

谁能知道并教我?非常感谢

class Program
{
    static void Main(string[] args)
    {
    //JsonResult is JSON string , input could be
    //{"total":1,"row":{"1":{"paper":"2330","pen":"","eraser":"","box":""}}}
    //or
    //{"total":3,"row":{"1":
    //{"paper":"0050","pen":"","eraser":"","box":""},"2":
    //{"paper":"0051","pen":"","eraser":"","box":""},"3":
    //{"paper":"0052","pen":"","eraser":"","box":""}}}
    //or
    //{"total":2163,"row":{"1":
    //{"paper":"0050","pen":"","eraser":"","box":""},"2":
    //{"paper":"0051","pen":"","eraser":"","box":""},"3":
    //{"paper":"0052","pen":"","eraser":"","box":""},.................}}
     RootObject root = JsonConvert.DeserializeObject<RootObject>(JsonResult);
      foreach (productType p in root.Contents)
      {
           Console.WriteLine(string.Format("{0}, {1}, {2}, {3})", p.paper, 
           p.pen, p.eraser, p.box));
      }

}

public class productType
{
     public string paper  { get; set; }
     public string pen { get; set; }
     public string eraser { get; set; }
     public string box { get; set; }
 }    
 public class RootObject
 {
      [JsonProperty("row")]
      public productType[] Contents { get; set; }
      public int total { get; set; }    
  }

a c#class不能以一个数字开头。您可以依靠[JsonProperty(PropertyName = "1")]1映射到productType,但仅适用于1。这不是解决方案。

[JsonProperty(PropertyName = "1")]
public class productType
{
    public string paper { get; set; }
    public string pen { get; set; }
    public string eraser { get; set; }
    public string box { get; set; }
}
public class Row
{
    public productType productType { get; set; }
}
public class RootObject
{
    public int total { get; set; }
    public Row row { get; set; }
}

那么什么?

您的JSON是您的问题。 row应该是rows,并且是项目的数组。类似:

{"total":3,"rows":[
{"paper":"0050","pen":"","eraser":"","box":""},
{"paper":"0051","pen":"","eraser":"","box":""},
{"paper":"0052","pen":"","eraser":"","box":""}]}

您的JSON结构的方式,行实际上表示为具有编号属性而不是数组的对象。您可以使用Dictionary<string, productType>而不是productType[]RootObject类中处理此操作。字典的键将是行号。这将适用于任何数量的行。

public class RootObject
{
    [JsonProperty("row")]
    public Dictionary<string, productType> Contents { get; set; }
    public int total { get; set; }    
}

这是一个带有3行的演示:https://dotnetfiddle.net/dwx4ri

相关内容

  • 没有找到相关文章

最新更新