我需要获得一个类似于以下内容的JSON字符串:
{"1":[{"value":"1", "text":"Basketball"}, {"value":"2", "text":"Tennis"}, {"value":"3", "text":"Football"}],"3":[{"value":"4", "text":"futbol"}]}
负责构建此代码的C#代码如下所示:
var sportsEntries = new Dictionary<byte, List<KeyValuePair<int, string>>>();
foreach (var department in Departments)
{
var deptOptions = SportList
.Where(x => x.DeptId == department.DeptId)
.ToDictionary(x => x.SportId, x => x.SportNameName).ToList();
sportsEntries .Add(department.DeptId, deptOptions);
}
var json = JsonConvert.SerializeObject(sportsEntries);
不幸的是,这种方法会生成错误的JSON。 JSON看起来像这样:
{"1":[{"Key":1,"Value":"Basketball"},{"Key":2,"Value":"Tennis"},{"Key":3,"Value":"Football"}],"3":[{"Key":4, "Value":"Futbol"}]}
我觉得我太近了。但是,我不确定如何更新我的C#代码以使生成的JSON看起来像我需要的格式。如何更新C#以输出正确的JSON?
谢谢!
答案 0 :(得分:3)
您可以使用以下内容:
var sportsEntries = new Dictionary<byte, List<object>();
foreach (var department in Departments)
{
var deptOptions = SportList
.Where(x => x.DeptId == department.DeptId)
.Select(x => new { value = x.SportId, text = x.SportNameName}).ToList();
sportsEntries .Add(department.DeptId, deptOptions);
}
var json = JsonConvert.SerializeObject(sportsEntries);
此解决方案用KeyValuePair<int, string>
替换初始object
并创建具有所需属性的匿名对象列表。
答案 1 :(得分:0)
这有效:
[TestFixture]
public class SoTest
{
[Test]
public void Test1()
{
var departments = new List<Department>
{
new Department
{
DeptId = 1
}
};
var sportList = new List<Sport>
{
new Sport
{
DeptId = 1,
SportId = 1,
SportName = "Basketball"
},
new Sport
{
DeptId = 1,
SportId = 2,
SportName = "Tennis"
}
};
var sportsEntries = new Dictionary<byte, List<Kvp>>();
foreach (var department in departments)
{
var deptOptions = sportList
.Where(x => x.DeptId == department.DeptId)
.Select(x => new Kvp { Value = x.SportId, Text = x.SportName }).ToList();
sportsEntries.Add(department.DeptId, deptOptions);
}
string json = JsonConvert.SerializeObject(sportsEntries);
Assert.IsNotNullOrEmpty(json);
Debug.Print(json);
}
}
public class Department
{
public byte DeptId { get; set; }
}
public class Sport
{
public byte DeptId { get; set; }
public int SportId { get; set; }
public string SportName { get; set; }
}
[DataContract]
public class Kvp
{
[DataMember(Name = "value")]
public int Value { get; set; }
[DataMember(Name = "text")]
public string Text { get; set; }
}