我无法打印p.paper
,p.pen
,p.eraser
,p.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; }
}
答案 0 :(得分:1)
C#类不能以数字开头。您可以依靠[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":""}]}
答案 1 :(得分:0)
您的JSON结构的方式,行实际上表示为具有编号属性而不是数组的对象。您可以使用RootObject
代替Dictionary<string, productType>
在productType[]
课程中处理此问题。字典的键是行号。这适用于任意数量的行。
public class RootObject
{
[JsonProperty("row")]
public Dictionary<string, productType> Contents { get; set; }
public int total { get; set; }
}
这是一个包含3行的演示:https://dotnetfiddle.net/dwX4RI