我想从我的sp返回特定类型的JSON格式。 以下是我想要的JSON格式:
我正在使用数据集从Query获取。 我已经遍历了表中的数据行。 我已经使用KeyValuPair类型来获取数据。 但是无法获取所需的格式,我只能获取格式键值,而如何获取元数据中的值。
我想要的JSON输出
{
"Metadata": [
{
"Key": "FirstName",
"Value": "ABC"
},
{
"Key": "LastName",
"Value": "XYZ"
}
],
"Length": 25,
"Type": "application/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;
我的班级结构
public class Class
{
public string FirstName{ get; set; }
public string LastName{ get; set; }
}
我得到的JSON格式
[{\"key":\"FirstName\", \"Value\":\"ABC\"},{\"key":\"LastName\", \"Value\":\"XYZ\"}]
我得到了键值JSON,但是它没有进入元数据数组中。
更新
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": "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",
}
差异
MetaData内的多余[],而我只需要一个数组。
答案 0 :(得分:0)
您必须创建一个类
public class Data {
public IList<KeyPairValue<string,string>> Metadata{ get; set; }
}
用您的值填充它,然后将其序列化为Json。
答案 1 :(得分:0)
答案根据评论进行更新
您的问题包括两个部分:
1。如何填充DataTable
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; }
}
然后,您应该使用Linq使用数据库查询结果填充dt
:
DataTable dt = new DataTable();
da.Fill(dt);
var listOfData = new Data
{
Metadata = dt.AsEnumerable()
.Select(m => new FullName
{
Key = m["FirstName"].ToString(),
Value = m["LastName"].ToString()
}).ToList(),
Length = 25,
Type = "application/mp3"
};
使用listOfData
命令将var json = JsonConvert.SerializeObject(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的外观并以自定义方式序列化它,则必须实现 Custon JsonConverter ,因为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);
}
}
然后以这种方式调用JsonObject.SerializeObject
,而不是一如既往地调用它:
var json = JsonConvert.SerializeObject(listOfData, Formatting.Indented /* set it depend on your need */, new CustomMetadataConverter<Metadata>());
您可以用相同的方法对它进行脱盐处理:
var deserializedObject = JsonConvert.DeserializeObject<JObject>(json, new CustomMetadataConverter<Metadata>());
以下是输出:
{
"Metadata": [
[
{
"Key": "FirstName",
"Value": "John"
},
{
"Key": "LastName",
"Value": "Smith"
}
],
[
{
"Key": "FirstName",
"Value": "Adele"
},
{
"Key": "LastName",
"Value": "Jones"
}
]
],
"Length": 25,
"Type": "application/json"
}
答案 2 :(得分:0)
您不需要像这样跳很多步。您可以说使用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);
编辑:尽管我觉得很奇怪,但这是使用罗斯文(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);