C# 如何在数组中获取键值json格式?
我想从我的sp返回一种特定类型的JSON格式。 下面是我想要的JSON格式: 我正在使用数据集从查询中获取数据。 我已经循环了表中的数据行。 我使用了KeyValuPair类型来获取数据。 但无法获得所需的格式,我只获取格式键值,但如何在元数据中获取该键值 我想要的JSON输出C# 如何在数组中获取键值json格式?,c#,asp.net-mvc,C#,Asp.net Mvc,我想从我的sp返回一种特定类型的JSON格式。 下面是我想要的JSON格式: 我正在使用数据集从查询中获取数据。 我已经循环了表中的数据行。 我使用了KeyValuPair类型来获取数据。 但无法获得所需的格式,我只获取格式键值,但如何在元数据中获取该键值 我想要的JSON输出 { "Metadata": [ { "Key": "FirstName", "Value": "ABC" }, { "Key": "LastName", "Value": "XYZ" } ], "Length": 25,
{
"Metadata": [
{
"Key": "FirstName",
"Value": "ABC"
},
{
"Key": "LastName",
"Value": "XYZ"
}
],
"Length": 25,
"Type": "application/mp3"
}
[{\"key":\"FirstName\", \"Value\":\"ABC\"},{\"key":\"LastName\", \"Value\":\"XYZ\"}]
{
"Metadata": [
[
{
"Key": "FirstName",
"Value": "ABC"
},
{
"Key": "LastName",
"Value": "DEF"
}
],
[
{
"Key": "FirstName",
"Value": "GEH"
},
{
"Key": "LastName",
"Value": "IJK"
}
]
],
"Length": 25,
"Type": "application/json"
}
{
"Metadata": [
{
"Key": "FirstName",
"Value": "ABC"
},
{
"Key": "LastName",
"Value": "XYZ"
}
],
"Length": 25,
"Type": "audio/mp3",
}
C#从sp获取数据的代码
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
List<Class> objList = new List<Class>();
List<KeyValuePair<string, string>> keyvalList = new List<KeyValuePair<string, string>>();
foreach (DataRow t in ds.Tables[0].Rows)
{
Class obj1 = new Class();
obj1.FirstName = Convert.ToString(t["FirstName "]);
obj1.LastName= Convert.ToString(t["LastName"]);
objList.Add(obj1);
keyvalList.Add(new KeyValuePair<string, string>("FirstName ", Convert.ToString(t["FirstName"])));
keyvalList.Add(new KeyValuePair<string, string>("LastName", Convert.ToString(t["LastName"]);
}
string JSONresult = JsonConvert.SerializeObject(keyvalList);
return JSONresult;
我得到的JSON格式
{
"Metadata": [
{
"Key": "FirstName",
"Value": "ABC"
},
{
"Key": "LastName",
"Value": "XYZ"
}
],
"Length": 25,
"Type": "application/mp3"
}
[{\"key":\"FirstName\", \"Value\":\"ABC\"},{\"key":\"LastName\", \"Value\":\"XYZ\"}]
{
"Metadata": [
[
{
"Key": "FirstName",
"Value": "ABC"
},
{
"Key": "LastName",
"Value": "DEF"
}
],
[
{
"Key": "FirstName",
"Value": "GEH"
},
{
"Key": "LastName",
"Value": "IJK"
}
]
],
"Length": 25,
"Type": "application/json"
}
{
"Metadata": [
{
"Key": "FirstName",
"Value": "ABC"
},
{
"Key": "LastName",
"Value": "XYZ"
}
],
"Length": 25,
"Type": "audio/mp3",
}
我得到了键值JSON,但它没有进入元数据数组
更新
public class Class
{
public string FirstName{ get; set; }
public string LastName{ get; set; }
}
var data = new
{
Metadata = dt.AsEnumerable()
.Select(m => new Header
{
key= m.Field<string>("AgentId"),
Value= m.Field<string>("LastName"),
FirstName = m["FirstName"].ToString(),
LastName = m["LastName"].ToString()
}).ToList(),
Length = "25",
Type = "application/mp3"
};
string JSONreult = JsonConvert.SerializeObject(data);
return JSONreult;
输出我想要的方式
{
"Metadata": [
{
"Key": "FirstName",
"Value": "ABC"
},
{
"Key": "LastName",
"Value": "XYZ"
}
],
"Length": 25,
"Type": "application/mp3"
}
[{\"key":\"FirstName\", \"Value\":\"ABC\"},{\"key":\"LastName\", \"Value\":\"XYZ\"}]
{
"Metadata": [
[
{
"Key": "FirstName",
"Value": "ABC"
},
{
"Key": "LastName",
"Value": "DEF"
}
],
[
{
"Key": "FirstName",
"Value": "GEH"
},
{
"Key": "LastName",
"Value": "IJK"
}
]
],
"Length": 25,
"Type": "application/json"
}
{
"Metadata": [
{
"Key": "FirstName",
"Value": "ABC"
},
{
"Key": "LastName",
"Value": "XYZ"
}
],
"Length": 25,
"Type": "audio/mp3",
}
差异
public class Class
{
public string FirstName{ get; set; }
public string LastName{ get; set; }
}
var data = new
{
Metadata = dt.AsEnumerable()
.Select(m => new Header
{
key= m.Field<string>("AgentId"),
Value= m.Field<string>("LastName"),
FirstName = m["FirstName"].ToString(),
LastName = m["LastName"].ToString()
}).ToList(),
Length = "25",
Type = "application/mp3"
};
string JSONreult = JsonConvert.SerializeObject(data);
return JSONreult;
额外的[]包含在元数据中,而我只需要一个数组。您必须创建一个类
public class Data {
public IList<KeyPairValue<string,string>> Metadata{ get; set; }
}
公共类数据{
公共IList元数据{get;set;}
}
用您的值填充它,然后将其序列化为Json。您必须创建一个类
public class Data {
public IList<KeyPairValue<string,string>> Metadata{ get; set; }
}
公共类数据{
公共IList元数据{get;set;}
}
用您的值填充它,然后将其序列化为Json。答案将根据注释更新 你的问题由两部分组成: 1.如何填充
数据表
2.如何将其序列化为json(定制外观)
首先,改变你的班级结构如下:
public class Metadata
{
public string FirstName { get; set; }
public string LasstName { get; set; }
}
public class Data
{
public IList<Metadata> Metadata { get; set; }
public int Length { get; set; }
public string Type { get; set; }
}
使用var json=JsonConvert.SerializeObject(listOfData)将listOfData
序列化为json后代码>命令,输出如下:
{
"Metadata":[
{
"Key":"John",
"Value":"Smith"
},
{
"Key":"Adele",
"Value":"Jones"
}
],
"Length":25,
"Type":"application/mp3"
}
但它与您期望的输出不同:
{
"Metadata":[
{
"Key":"FirstName",
"Value":"John"
},
{
"Key":"LastName",
"Value":"Smith"
}
],
"Length":25,
"Type":"application/mp3"
}
如果您希望更改json的外观并以自定义方式对其进行序列化,则必须实现一个,因为JsonSerializer本身无法更改您的模型。为此,您必须创建一个类,并从JsonConverter
派生该类,并重写其方法以根据需要塑造节点:
class CustomMetadataConverter<T> : JsonConverter where T : class
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(T);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject obj = new JObject(
JArray.Load(reader)
.Children<JObject>()
.Select(jo => new JProperty((string)jo["Key"], jo["Value"]))
);
T result = Activator.CreateInstance<T>();
serializer.Populate(obj.CreateReader(), result);
return result;
}
public override bool CanRead
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JArray array = new JArray(
JObject.FromObject(value)
.Properties()
.Select(jp =>
new JObject(
new JProperty("Key", jp.Name),
new JProperty("Value", jp.Value)
)
)
);
array.WriteTo(writer);
}
}
您可以使用相同的方法对其进行去序列化:
var deserializedObject = JsonConvert.DeserializeObject<JObject>(json, new CustomMetadataConverter<Metadata>());
根据评论更新答案
你的问题由两部分组成:
1.如何填充数据表
2.如何将其序列化为json(定制外观)
首先,改变你的班级结构如下:
public class Metadata
{
public string FirstName { get; set; }
public string LasstName { get; set; }
}
public class Data
{
public IList<Metadata> Metadata { get; set; }
public int Length { get; set; }
public string Type { get; set; }
}
使用var json=JsonConvert.SerializeObject(listOfData)将listOfData
序列化为json后代码>命令,输出如下:
{
"Metadata":[
{
"Key":"John",
"Value":"Smith"
},
{
"Key":"Adele",
"Value":"Jones"
}
],
"Length":25,
"Type":"application/mp3"
}
但它与您期望的输出不同:
{
"Metadata":[
{
"Key":"FirstName",
"Value":"John"
},
{
"Key":"LastName",
"Value":"Smith"
}
],
"Length":25,
"Type":"application/mp3"
}
如果您希望更改json的外观并以自定义方式对其进行序列化,则必须实现一个,因为JsonSerializer本身无法更改您的模型。为此,您必须创建一个类,并从JsonConverter
派生该类,并重写其方法以根据需要塑造节点:
class CustomMetadataConverter<T> : JsonConverter where T : class
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(T);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject obj = new JObject(
JArray.Load(reader)
.Children<JObject>()
.Select(jo => new JProperty((string)jo["Key"], jo["Value"]))
);
T result = Activator.CreateInstance<T>();
serializer.Populate(obj.CreateReader(), result);
return result;
}
public override bool CanRead
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JArray array = new JArray(
JObject.FromObject(value)
.Properties()
.Select(jp =>
new JObject(
new JProperty("Key", jp.Name),
new JProperty("Value", jp.Value)
)
)
);
array.WriteTo(writer);
}
}
您可以使用相同的方法对其进行去序列化:
var deserializedObject = JsonConvert.DeserializeObject<JObject>(json, new CustomMetadataConverter<Metadata>());
你不需要像那样跳很多次。您可以说使用LinqToSQL或LinqToEF,以及来自NuGet的Newtonsoft的Json.Net,您的代码如下所示:
var data = new
{
MetaData = db.TableName
.Select(row => new { Key = row.FieldForKey, Value = row.FieldForValue }),
Length = 25,
Type = "application/mp3"
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
如果您仍然想使用ADO.Net,您仍然可以这样做:
var tbl = new DataTable();
new SqlDataAdapter(cmd, "your connection string here").Fill(tbl);
var data = new
{
MetaData = tbl.AsEnumerable()
.Select(t => new { Key = t.Field<string>("KeyColumn"), Value = t.Field<string>("ValueColumn")}),
Length = 25,
Type = "application/mp3"
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
var tbl=new DataTable();
新的SqlDataAdapter(cmd,“此处的连接字符串”).Fill(tbl);
var数据=新
{
元数据=tbl.AsEnumerable()
.Select(t=>new{Key=t.Field(“KeyColumn”),Value=t.Field(“ValueColumn”)}),
长度=25,
Type=“应用程序/mp3”
};
var json=Newtonsoft.json.JsonConvert.SerializeObject(数据);
编辑:虽然我觉得很奇怪,但下面是使用Northwind示例数据库的完整示例:
var tbl = new DataTable();
new SqlDataAdapter(@"Select t.*
from Customers c1
cross apply (select 'FirstName', customerId from customers c2 where c1.CustomerId = c2.CustomerId
union
select 'LastName', CompanyName from customers c2 where c1.CustomerId = c2.CustomerId) t([Key], [Value])
",@"server=.\SQLExpress2012;Database=Northwind;Trusted_Connection=yes").Fill(tbl);
var data = new
{
MetaData = tbl.AsEnumerable()
.Select(t => new {
Key = t.Field<string>("Key"),
Value = t.Field<string>("Value") } ),
Length = 25,
Type = "application/mp3"
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
var tbl=new DataTable();
新建SqlDataAdapter(@“选择t.*
来自客户c1
交叉应用(从customers c2中选择“FirstName”,customerId,其中c1.customerId=c2.customerId
联盟
从客户c2中选择“LastName”,其中c1.CustomerId=c2.CustomerId)t([Key],[Value])
“,@”服务器=。\SQLExpress2012;数据库=北风;可信连接=是”).Fill(tbl);
var数据=新
{
元数据=tbl.AsEnumerable()
.Select(t=>new{
Key=t.字段(“Key”),
Value=t.Field(“Value”)}),
长度=25,
Type=“应用程序/mp3”
};
var json=Newtonsoft.json.JsonConvert.SerializeObject(数据);
你不需要像那样跳很多次。您可以说使用LinqToSQL或LinqToEF,以及来自NuGet的Newtonsoft的Json.Net,您的代码如下所示:
var data = new
{
MetaData = db.TableName
.Select(row => new { Key = row.FieldForKey, Value = row.FieldForValue }),
Length = 25,
Type = "application/mp3"
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
如果您仍然想使用ADO.Net,您仍然可以这样做:
var tbl = new DataTable();
new SqlDataAdapter(cmd, "your connection string here").Fill(tbl);
var data = new
{
MetaData = tbl.AsEnumerable()
.Select(t => new { Key = t.Field<string>("KeyColumn"), Value = t.Field<string>("ValueColumn")}),
Length = 25,
Type = "application/mp3"
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
var tbl=new DataTable();
新的SqlDataAdapter(cmd,“此处的连接字符串”).Fill(tbl);
var数据=新
{
元数据=tbl.AsEnumerable()
.Select(t=>new{Key=t.Field(“KeyColumn”),Value=t.Field(“ValueColumn”)}),
长度=25,
Type=“应用程序/mp3”
};
var json=Newtonsoft.json.JsonConvert.SerializeObject(数据);
编辑:虽然我觉得很奇怪,但下面是使用Northwind示例数据库的完整示例:
var tbl = new DataTable();
new SqlDataAdapter(@"Select t.*
from Customers c1
cross apply (select 'FirstName', customerId from customers c2 where c1.CustomerId = c2.CustomerId
union
select 'LastName', CompanyName from customers c2 where c1.CustomerId = c2.CustomerId) t([Key], [Value])
",@"server=.\SQLExpress2012;Database=Northwind;Trusted_Connection=yes").Fill(tbl);
var data = new
{
MetaData = tbl.AsEnumerable()
.Select(t => new {
Key = t.Field<string>("Key"),
Value = t.Field<string>("Value") } ),
Length = 25,
Type = "application/mp3"
};
var json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
var tbl=new DataTable();
新建SqlDataAdapter(@“选择t.*
来自客户c1
交叉应用(从customers c2中选择“FirstName”,customerId,其中c1.customerId=c2.customerId
联盟
从客户c2中选择“LastName”,其中c1.CustomerId=c2.CustomerId)t([Key],[Value])
“,@”服务器=。\SQLExpress2012;数据库=北风;可信连接=是”).Fill(tbl);
var数据=新
{
元数据=tbl.AsEnumerable()
.Select(t=>new{
Key=t.字段(“Key”),
Value=t.Field(“Value”)}),
长度=25,
Type=“应用程序/mp3”
};
var json=Newtonsoft.json.JsonConvert.SerializeObject(数据);
如何从此类类结构的数据集中循环?此外,我正在使用dataset DataAdapter从sp获取数据。因此,我需要一个键值和数组中的其他正常JSON.outer数据,如“Len”