是否有方法将JSON内容反序列化为c#动态类型?为了使用DataContractJsonSerializer,最好跳过创建一堆类。
当前回答
如何解析简单的JSON内容与动态& JavaScriptSerializer
请添加System.Web.Extensions的引用,并使用System.Web.Script.Serialization添加此命名空间;在前:
public static void EasyJson()
{
var jsonText = @"{
""some_number"": 108.541,
""date_time"": ""2011-04-13T15:34:09Z"",
""serial_number"": ""SN1234""
}";
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<dynamic>(jsonText);
Console.WriteLine(dict["some_number"]);
Console.ReadLine();
}
如何解析嵌套和复杂的json与动态和JavaScriptSerializer
请添加System.Web.Extensions的引用,并使用System.Web.Script.Serialization添加此命名空间;在前:
public static void ComplexJson()
{
var jsonText = @"{
""some_number"": 108.541,
""date_time"": ""2011-04-13T15:34:09Z"",
""serial_number"": ""SN1234"",
""more_data"": {
""field1"": 1.0,
""field2"": ""hello""
}
}";
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<dynamic>(jsonText);
Console.WriteLine(dict["some_number"]);
Console.WriteLine(dict["more_data"]["field2"]);
Console.ReadLine();
}
其他回答
使用DataSet(c#)和JavaScript。一个创建带有DataSet输入的JSON流的简单函数。创建JSON内容,如(多表数据集):
[[{a:1,b:2,c:3},{a:3,b:5,c:6}],[{a:23,b:45,c:35},{a:58,b:59,c:45}]]
只是客户端,使用eval。例如,
var d = eval('[[{a:1,b:2,c:3},{a:3,b:5,c:6}],[{a:23,b:45,c:35},{a:58,b:59,c:45}]]')
然后使用:
d[0][0].a // out 1 from table 0 row 0
d[1][1].b // out 59 from table 1 row 1
// Created by Behnam Mohammadi And Saeed Ahmadian
public string jsonMini(DataSet ds)
{
int t = 0, r = 0, c = 0;
string stream = "[";
for (t = 0; t < ds.Tables.Count; t++)
{
stream += "[";
for (r = 0; r < ds.Tables[t].Rows.Count; r++)
{
stream += "{";
for (c = 0; c < ds.Tables[t].Columns.Count; c++)
{
stream += ds.Tables[t].Columns[c].ToString() + ":'" +
ds.Tables[t].Rows[r][c].ToString() + "',";
}
if (c>0)
stream = stream.Substring(0, stream.Length - 1);
stream += "},";
}
if (r>0)
stream = stream.Substring(0, stream.Length - 1);
stream += "],";
}
if (t>0)
stream = stream.Substring(0, stream.Length - 1);
stream += "];";
return stream;
}
最简单的方法是:
只需包含这个DLL文件。
像这样使用代码:
dynamic json = new JDynamic("{a:'abc'}");
// json.a is a string "abc"
dynamic json = new JDynamic("{a:3.1416}");
// json.a is 3.1416m
dynamic json = new JDynamic("{a:1}");
// json.a is
dynamic json = new JDynamic("[1,2,3]");
/json.Length/json.Count is 3
// And you can use json[0]/ json[2] to get the elements
dynamic json = new JDynamic("{a:[1,2,3]}");
//json.a.Length /json.a.Count is 3.
// And you can use json.a[0]/ json.a[2] to get the elements
dynamic json = new JDynamic("[{b:1},{c:1}]");
// json.Length/json.Count is 2.
// And you can use the json[0].b/json[1].c to get the num.
我需要的是返回一个带有不同字段的json模型。 我的模型是这样的,但它可以改变。
{
"employees":
[
{ "name": "Darth", "surname": "Vader", "age": "27", "department": "finance"},
{ "name": "Luke", "surname": "Skywalker", "age": "25", "department": "IT"},
{ "name": "Han", "surname": "Solo", "age": "26", "department": "credit"}
]
}
获取数据值的列表
JObject array = JObject.Parse(model.JsonData);
var tableData = new List<JsonDynamicModel>();
foreach (var objx in array.Descendants().OfType<JProperty>().Where(p => p.Value.Type != JTokenType.Array && p.Value.Type != JTokenType.Object))
{
var name = ((JValue)objx.Name).Value;
var value = ((JValue)objx.Value).Value;
if (tableData.FirstOrDefault(x => x.ColumnName == name.ToString()) == null)
{
tableData.Add(new JsonDynamicModel
{
ColumnName = name.ToString(),
Values = new List<string> { value.ToString() },
});
}
else
{
tableData.FirstOrDefault(x=>x.ColumnName == name.ToString()).Values.Add(value.ToString());
}
}
输出如下所示。然后我把结果模型转换成一个html表,我用这个方法创建了一个html表
// output
tableData[0].ColumnName -> "name";
tableData[0].Values -> {"Darth", "Luke", "Han" }
tableData[1].ColumnName -> "surname";
tableData[1].Values -> {"Vader", "Skywalker", "Solo" }
...
JsonFx可以将JSON内容反序列化为动态对象。
序列化动态类型(.NET 4.0的默认值):
var reader = new JsonReader(); var writer = new JsonWriter();
string input = @"{ ""foo"": true, ""array"": [ 42, false, ""Hello!"", null ] }";
dynamic output = reader.Read(input);
Console.WriteLine(output.array[0]); // 42
string json = writer.Write(output);
Console.WriteLine(json); // {"foo":true,"array":[42,false,"Hello!",null]}
你可以扩展JavaScriptSerializer来递归复制它创建的字典来扩展对象,然后动态地使用它们:
static class JavaScriptSerializerExtensions
{
public static dynamic DeserializeDynamic(this JavaScriptSerializer serializer, string value)
{
var dictionary = serializer.Deserialize<IDictionary<string, object>>(value);
return GetExpando(dictionary);
}
private static ExpandoObject GetExpando(IDictionary<string, object> dictionary)
{
var expando = (IDictionary<string, object>)new ExpandoObject();
foreach (var item in dictionary)
{
var innerDictionary = item.Value as IDictionary<string, object>;
if (innerDictionary != null)
{
expando.Add(item.Key, GetExpando(innerDictionary));
}
else
{
expando.Add(item.Key, item.Value);
}
}
return (ExpandoObject)expando;
}
}
然后,您只需要为您在其中定义扩展的名称空间使用一个using语句(考虑在System.Web.Script.Serialization中定义它们…)另一个技巧是不使用命名空间,那么你根本不需要using语句),你可以像这样使用它们:
var serializer = new JavaScriptSerializer();
var value = serializer.DeserializeDynamic("{ 'Name': 'Jon Smith', 'Address': { 'City': 'New York', 'State': 'NY' }, 'Age': 42 }");
var name = (string)value.Name; // Jon Smith
var age = (int)value.Age; // 42
var address = value.Address;
var city = (string)address.City; // New York
var state = (string)address.State; // NY