[英]c# json parsing format
In c#, I'm trying to parse JSON that is in the following format. 在c#中,我试图解析以下格式的JSON。 I've only been able to come close using the example code below, but it is very unstable. 我只能使用下面的示例代码来接近,但是它非常不稳定。
(I'm also not sure how to parse in Javascript, which I also need to do.) (我也不确定如何用Javascript解析,这也是我需要做的。)
JSON example: JSON示例:
{"72": { "Rejected": true }, "271": { "PreApproved": true}}
Code example: 代码示例:
List<SSKChanges> lstSSK = new List<SSKChanges>();
string sskSource = "";
string sskStatus = "";
bool sskStatusBool = false;
int i = 0;
int iList = 0;
JsonTextReader reader = new JsonTextReader(new StringReader(jsonExample));
while (reader.Read())
{
if (reader.Value != null)
{
if (i == 0)
{
int n;
bool isNumeric = int.TryParse(reader.Value.ToString(), out n);
if (isNumeric)
{
sskSource = reader.Value.ToString();
i = 1;
}
else
{
sskStatus = reader.Value.ToString();
i = 2;
}
}
else if (i == 1)
{
sskStatus = reader.Value.ToString();
i = 2;
}
else
{
sskStatusBool = (bool)reader.Value;
i = 0;
sskSource = "";
sskStatus = "";
sskStatusBool = false;
}
}
}
Assuming you are already using json.net (as is suggested by your use of JsonTextReader
), you can load your JSON into a JObject
then query the resulting object with LINQ to JSON . 假设您已经在使用json.net (如使用JsonTextReader所建议的JsonTextReader
),则可以将JSON加载到JObject
然后使用LINQ to JSON 查询生成的对象。
For instance, given the class: 例如,给定类:
public class SSKChanges
{
public string SskSource { get; set; }
public string SskStatus { get; set; }
public bool? SskStatusBool { get; set; }
}
You can do: 你可以做:
var obj = JObject.Parse(jsonExample);
var lstSSK = (from property in obj.Properties()
select new SSKChanges
{
SskSource = property.Name,
SskStatus = property.Value.Children<JProperty>().Select(p2 => p2.Name).FirstOrDefault(),
SskStatusBool = property.Value.Children<JProperty>().Select(p2 => (bool?)p2.Value).FirstOrDefault()
}).ToList();
As for the second question in your question, i'm also not sure how to parse in javascript, I need to do that too , you should ask a second question directed specifically at javascript experts. 至于您问题中的第二个问题, 我也不确定如何用javascript解析,我也需要这样做 ,您应该问一个专门针对javascript专家的第二个问题。
Since you are already using Json.net, I would do it as: 由于您已经在使用Json.net,因此我可以这样做:
string json = @"{""72"": { ""Rejected"": true }, ""271"": { ""PreApproved"": true}}";
var jobj = JObject.Parse(json);
foreach (var entry in jobj.Children().Cast<JProperty>())
{
var kv = entry.Value.First() as JProperty;
Console.WriteLine(entry.Name + "=>" + kv.Name + ":" + kv.Value);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.