C#解析Json动态对象
我可以通过以下JSon循环使用一些帮助:C#解析Json动态对象,c#,json,dynamic,C#,Json,Dynamic,我可以通过以下JSon循环使用一些帮助: string jsonobj = "[{'LastTighteningResultDataRev3': 'Header', 'Attribute': ['Length','1','4']}, {'LastTighteningResultDataRev3': 'Header', 'Attribute': ['MID','5','4']}, {'LastTighteningResultDataRev3': 'Header', 'Attrib
string jsonobj = "[{'LastTighteningResultDataRev3': 'Header', 'Attribute': ['Length','1','4']},
{'LastTighteningResultDataRev3': 'Header', 'Attribute': ['MID','5','4']},
{'LastTighteningResultDataRev3': 'Header', 'Attribute': ['REV','9','3']},
{'LastTighteningResultDataRev3': 'DataFields', 'Attribute': ['CellID','21','2','23','3']},
{'LastTighteningResultDataRev3': 'DataFields', 'Attribute': ['ChannelID','27','2','29','2']}]";
我将JSon反序列化为动态:
#region "Parse Data Schema"
var tempObj = new[] { new { LastTighteningResultDataRev3 = "", Attribute = new List<string>() } };
var deserializedObject = JsonConvert.DeserializeAnonymousType(jsonobj, tempObj);
#endregion
我没有选择使用此代码,但如果您需要将选择限制为“数据字段”,则此代码将起作用:
var deserializedList = JsonConvert.DeserializeAnonymousType(LastTighteningResultDT.Rows[0]["DataSchema"].ToString(), tempObj).ToList();
deserializedList.Where(x => x.LastTighteningResultDataRev3 =="DataFields").Select(y => y.Attribute).ToList().ForEach(attrs =>
{
{
acoplasttighteningresultdatacs.p_Attribute = attrs[0];
acoplasttighteningresultdatacs.p_AttributeIDStartPosition = attrs[1];
acoplasttighteningresultdatacs.p_AttributeIDLength = attrs[2];
#region "Load attribute values from controller response mesage"
acoplasttighteningresultdatacs.p_AttributeIDValue =
testRequestResponseInfo.p_TestResult.Substring(Convert.ToInt16(acoplastThreadingResultDatacs.p_AttributeIDStartPosition)-1,
转换为NT16(acoplast拧紧结果数据cs.p_AttributeIDLength);
#端区
acoplast拧紧结果数据cs.p_AttributeValueStartPosition=attrs[3];
AcoplastTenstengResultDatacs.p_AttributeValueStartLength=attrs[4];
#区域“从控制器响应表加载属性值”
Acoplast拧紧结果数据cs.p_属性值=
TestRequestResponseInfo.p_TestResult.Substring(转换为16(acoplastThreadingResultDatacs.p_AttributeValueStartPosition)-1,
转换为NT16(acoplastTensingResultDatacs.p_AttributeValueAstartLength);
#端区
if (acoplasttighteningresultdatacs.LoadACOPLastTighteningResultDataGLRepository()) return;
}
});
需要检索业务规则的属性信息;因此,我将上一个结果数据存储库加载到一个字典中,这样可以方便地查看属性信息。这样,如果模式信息发生更改,解决方案仍然能够找到属性信息。(即拧紧状态)。它将为所有业务规则属性和所有必须通过的属性找到最后的结果数据
#region "Static ACOPLastTighteningResultDataCS Dictionary"
public static Dictionary<int, ACOPLastTighteningResultDataCS> ACOPLastTighteningResultDataDictionary = new Dictionary<int, ACOPLastTighteningResultDataCS>();
#endregion
#region "Static ACOPLastTighteningResultDataRepositoryForAttribute"
public static List<ACOPLastTighteningResultDataCS> ACOPLastTighteningResultDataRepositoryForAttribute = new List<ACOPLastTighteningResultDataCS>();
#endregion
#region "Validate by Business Rule Type"
bool ValidatedSW = false;
switch (Convert.ToInt32(BusinessRuleInfoDT.Rows[0]["BusinessRuleTypeInfoID"].ToString()))
{
case ((int)BusinessRuleTypes.Length):
{
if (gvTestActions.Rows[gvTestActions.CurrentRow.Index].Cells[(int)gvCols.ScannedInValue].Value.ToString().Trim().Length == Convert.ToInt32(BusinessRuleInfoDT.Rows[0]["Value"])) ValidatedSW = true;
break;
}
case ((int)BusinessRuleTypes.Contains):
{
ValidatedSW = false;
break;
}
case ((int)BusinessRuleTypes.Compare):
{
if (!(ACOPLastTighteningResultDataCS.LoadACOPLastTighteningResultDataDictionary())) break;
if (!(ACOPLastTighteningResultDataCS.GetACOPLastTighteningResultDataByAttributeID(Convert.ToInt32(BusinessRuleInfoDT.Rows[0]["AttributeID"])))) return;
if (Convert.ToInt32(ACOPLastTighteningResultDataCS.ACOPLastTighteningResultDataRepositoryForAttribute[0].p_AttributeValue) == Convert.ToInt32(BusinessRuleInfoDT.Rows[0]["Value"])) ValidatedSW = true;
break;
}
case ((int)BusinessRuleTypes.ValidRange):
{
ValidatedSW = false;
break;
}
case ((int)BusinessRuleTypes.Authorize):
{
ValidatedSW = false;
break;
}
}
下面是从dictionary方法获取属性id。我将其加载到静态通用列表中,以便访问UI线程上的值:
#region "GetACOPLastTighteningResultDataByAttributeID"
public static bool GetACOPLastTighteningResultDataByAttributeID(int AttributeID)
{
try
{
ACOPLastTighteningResultDataCS acopLastTighteningResultDataGLRepository;
if (!(ACOPLastTighteningResultDataDictionary.TryGetValue(AttributeID, out acopLastTighteningResultDataGLRepository))) return false;
ACOPLastTighteningResultDataRepositoryForAttribute.Add(new ACOPLastTighteningResultDataCS
{
p_AttributeIDStartPosition = acopLastTighteningResultDataGLRepository.p_AttributeIDStartPosition,
p_AttributeIDLength = acopLastTighteningResultDataGLRepository.p_AttributeIDLength,
p_Attribute = acopLastTighteningResultDataGLRepository.p_Attribute,
p_AttributeIDValue = acopLastTighteningResultDataGLRepository.p_AttributeIDValue,
p_AttributeValue = acopLastTighteningResultDataGLRepository.p_AttributeValue,
p_AttributeValueStartPosition = acopLastTighteningResultDataGLRepository.p_AttributeValueStartPosition,
p_AttributeValueStartLength = acopLastTighteningResultDataGLRepository.p_AttributeValueStartLength
});
return true;
}
catch (Exception ex)
{
return false;
}
}
#endregion
如果你真的需要它是动态的,那么使用帕维尔的答案 如果不是,我建议如下:
public class LastTighteningResultData {
public string LastTighteningResultDataRev3 {get;set;}
public IEnumerable<string> Attribute {get;set;}
}
var data = JsonConvert.DeserializeObject<LastTighteningResultData[]>(jsonobj);
foreach (var resultData in data)
{
// do stuff here with resultData.LastTighteningResultDataRev3 & resultData.Attribute
}
public类lastTenningResultData{
公共字符串LastThreadingResultDataRev3{get;set;}
公共IEnumerable属性{get;set;}
}
var data=JsonConvert.DeserializeObject(jsonobj);
foreach(数据中的var resultData)
{
//使用resultData.lastThreadingResultDataRev3和resultData.Attribute在此处执行操作
}
通过强输入数据,您可以让一切变得更加简单。您可以使用Newtonsoft的JsonConvert.DeserializeAnonymousType来实现此目的
string jsonobj = @"[{'LastTighteningResultDataRev3': 'Header', 'Attribute': ['Length','1','4']},
{ 'LastTighteningResultDataRev3': 'Header', 'Attribute': ['MID','5','4']
},
{'LastTighteningResultDataRev3': 'Header', 'Attribute': ['REV','9','3']
},
{'LastTighteningResultDataRev3': 'DataFields', 'Attribute': ['CellID','21','2','23','3']},
{'LastTighteningResultDataRev3': 'DataFields', 'Attribute': ['ChannelID','27','2','29','2']}]";
var tempObj = new[] {
new {
LastTighteningResultDataRev3 = "",
Attribute = new List<string>()
}
};
var deserializedObject = JsonConvert.DeserializeAnonymousType(jsonobj, tempObj);
deserializedObject.ToList().ForEach(x => {
//you can access x.LastTighteningResultDataRev3
//you can access x.attributes
x.Attribute.ForEach(a =>
{
//loop through attributes
});
});
string jsonobj=@“[{'lastTenningResultDataRev3':'Header','Attribute':['Length','1','4'],
{'LastThreadingResultDataRev3':'Header','Attribute':['MID','5','4']
},
{'LastThreadingResultDataRev3':'Header','Attribute':['REV','9','3']
},
{'LastTenningResultDataRev3':'DataFields','Attribute':['CellID','21','2','23','3'],
{'LastTenningResultDataRev3':'DataFields','Attribute':['ChannelID','27','2','29','2']}];
var tempObj=new[]{
新的{
最后拧紧结果数据版本3=“”,
属性=新列表()
}
};
var deserializedObject=JsonConvert.DeserializeAnonymousType(jsonobj,tempObj);
反序列化对象.ToList().ForEach(x=>{
//您可以访问x.LastSteeringResultDataRev3
//您可以访问x.attributes
x、 Attribute.ForEach(a=>
{
//循环遍历属性
});
});
为什么要使用动态密码?这个数据结构可能会改变吗?现在所有对象都具有相同的字段。如果您真的希望它是动态的,您可能应该使用一个模型并反序列化到一个类型foreach(jsondynamic中的动态项)
工作。这是否回答了您的问题?你需要什么帮助?你想在每个循环中做什么?我不同意无效的循环。字符串分隔符为“
不是”
。这是不标准的。但是使用,您应该能够毫无问题地解析它。接收以下错误消息:foreach语句无法对object类型的变量进行操作,因为object不包含GetEnumerator的公共实例定义。请就如何解决此问题提供建议。抱歉,我在示例中遗漏了一些内容。我将更新它。您需要使用反序列化对象的通用版本,并指定您希望反序列化的类型。反序列化对象(jsonobj);这对我有用!不确定这是否是适合我的情况的最佳解决方案,但感谢您的帮助。在循环遍历属性的同时,如何在标题和数据字段之间进行过滤?如果您想在标题和数据字段之间进行过滤,那么您可以这样做:var deserializedList=JsonConvert.DeserializeAnonymousType(jsonobj,tempObj).ToList();反序列化列表。其中(x=>x.LastThreadingResultDataRev3==“Header”)。选择(y=>y.Attribute).ToList().ForEach(attrs=>{//现在您可以只循环使用头属性attrs.ForEach(attr=>{Console.WriteLine(attr);});
public class LastTighteningResultData {
public string LastTighteningResultDataRev3 {get;set;}
public IEnumerable<string> Attribute {get;set;}
}
var data = JsonConvert.DeserializeObject<LastTighteningResultData[]>(jsonobj);
foreach (var resultData in data)
{
// do stuff here with resultData.LastTighteningResultDataRev3 & resultData.Attribute
}
string jsonobj = @"[{'LastTighteningResultDataRev3': 'Header', 'Attribute': ['Length','1','4']},
{ 'LastTighteningResultDataRev3': 'Header', 'Attribute': ['MID','5','4']
},
{'LastTighteningResultDataRev3': 'Header', 'Attribute': ['REV','9','3']
},
{'LastTighteningResultDataRev3': 'DataFields', 'Attribute': ['CellID','21','2','23','3']},
{'LastTighteningResultDataRev3': 'DataFields', 'Attribute': ['ChannelID','27','2','29','2']}]";
var tempObj = new[] {
new {
LastTighteningResultDataRev3 = "",
Attribute = new List<string>()
}
};
var deserializedObject = JsonConvert.DeserializeAnonymousType(jsonobj, tempObj);
deserializedObject.ToList().ForEach(x => {
//you can access x.LastTighteningResultDataRev3
//you can access x.attributes
x.Attribute.ForEach(a =>
{
//loop through attributes
});
});