将带有空格的JSON属性解析为对象
我正在使用一个返回JSON的第三方系统 我正在尝试解决如何反序列化以下json将带有空格的JSON属性解析为对象,json,json.net,Json,Json.net,我正在使用一个返回JSON的第三方系统 我正在尝试解决如何反序列化以下json {"getResponse": { "Results": { "Result 1": {"Row": [{Name:Somename}] } } 我正在使用Newtonsoft JSON库。有人知道我如何将其解析为.Net对象吗?我希望有更好的方法来实现这一点,因此我发布这篇文章是希望有人能提供更好的答案 给出以下(更正的)JSON 我想对行数组中的元素进行反序列化,但不确定如何使
{"getResponse": {
"Results": {
"Result 1": {"Row": [{Name:Somename}]
}
}
我正在使用Newtonsoft JSON库。有人知道我如何将其解析为.Net对象吗?我希望有更好的方法来实现这一点,因此我发布这篇文章是希望有人能提供更好的答案 给出以下(更正的)JSON 我想对行数组中的元素进行反序列化,但不确定如何使用自定义转换器进行反序列化 因此,在我有时间找到更好的方法之前,我的解决方案是:
JObject result = JObject.Parse(response);
var t = result["getResponse"]["Results"]["Result 1"]["Row"];
var els =
JsonConvert.DeserializeObject<List<MyResponse>>(t.ToString());
JObject result=JObject.Parse(响应);
var t=result[“getResponse”][“Results”][“result 1”][“Row”];
变量els=
反序列化对象(t.ToString());
要使用JsonConvert.DeserializeObject
将JSON解析为对象,您可以将类结构如下所示:
public class RootObject
{
public GetResponse getResponse { get; set; }
}
public class GetResponse
{
public Results Results { get; set; }
}
public class Results
{
[JsonProperty("Result 1")]
public Result1 Result1 { get; set; }
}
public class Result1
{
[JsonProperty("Row")]
public List<Row> Rows { get; set; }
}
public class Row
{
public string Name { get; set; }
}
string json = @"
{
""getResponse"": {
""Results"": {
""Result 1"": {
""Row"": [
{
""Name"": ""Somename""
}
]
}
}
}
}";
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
foreach (Row row in root.getResponse.Results.Result1.Rows)
{
Console.WriteLine(row.Name);
}
公共类根对象
{
公共GetResponse GetResponse{get;set;}
}
公共类GetResponse
{
公共结果{get;set;}
}
公开课成绩
{
[JsonProperty(“结果1”)]
public Result1 Result1{get;set;}
}
公开课成绩1
{
[JsonProperty(“Row”)]
公共列表行{get;set;}
}
公共类行
{
公共字符串名称{get;set;}
}
然后像这样反序列化:
public class RootObject
{
public GetResponse getResponse { get; set; }
}
public class GetResponse
{
public Results Results { get; set; }
}
public class Results
{
[JsonProperty("Result 1")]
public Result1 Result1 { get; set; }
}
public class Result1
{
[JsonProperty("Row")]
public List<Row> Rows { get; set; }
}
public class Row
{
public string Name { get; set; }
}
string json = @"
{
""getResponse"": {
""Results"": {
""Result 1"": {
""Row"": [
{
""Name"": ""Somename""
}
]
}
}
}
}";
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
foreach (Row row in root.getResponse.Results.Result1.Rows)
{
Console.WriteLine(row.Name);
}
stringjson=@”
{
“getResponse”:{
“结果”:{
“结果1”:{
“行”:[
{
“名称”:“某物名称”
}
]
}
}
}
}";
RootObject root=JsonConvert.DeserializeObject(json);
foreach(root.getResponse.Results.Result1.Rows中的行)
{
Console.WriteLine(行名称);
}
通常您会使用obj['Result 1']
而不是obj->Result 1
,无论您选择的.net语言中有什么等价物。这是无效的JSON(可能只是问题中的“输入错误”)。不,这不是输入错误。字段名用引号括起来并且有效。请看是否存在一些固定的结果集,或者可能存在任意数量的结果集?这是一个用于分析json的有用网站。您可以看到它不喜欢您的代码片段。您是生成这个json还是从外部源提供的?但是,我要做的是使用JsonConvert.DeserializeObject方法。但是,我不确定给定JSON需要什么样的类结构。