我对.Net Json序列化有点问题 我有类列表的类,我需要将它序列化为属性,例如:
原:
class:
kid{
int age;
String name;
List[String] toys;
}
结果:
{
"age":10,
"name": Jane,
"toys":["one", "two", "three"]
}
我需要
{
"age":10,
"name": Jane,
"toy_1": "one",
"toy_2": "two",
"toy_3": "three"
}
这是因为api。有什么方法可以做到吗?
答案 0 :(得分:3)
这是一个不假设玩具数量的动态解决方案:
public class kid
{
public int age;
public String name;
public List<String> toys;
public string ApiCustomView
{
get
{
Dictionary<string, string> result = new Dictionary<string, string>();
result.Add("age", age.ToString());
result.Add("name", name);
for (int ii = 0; ii < toys.Count; ii++)
{
result.Add(string.Format("toy_{0}", ii), toys[ii]);
}
return result.ToJSON();
}
}
}
用法:
static void Main(string[] args)
{
var k = new kid { age = 23, name = "Paolo", toys = new List<string>() };
k.toys.Add("Pippo");
k.toys.Add("Pluto");
Console.WriteLine(k.ApiCustomView);
Console.ReadLine();
}
它使用您可以在此处找到的扩展程序:How to create JSON string in C#
namespace ExtensionMethods
{
public static class JSONHelper
{
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
public static string ToJSON(this object obj, int recursionDepth)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RecursionLimit = recursionDepth;
return serializer.Serialize(obj);
}
}
}
答案 1 :(得分:1)
正如dcastro所说,它是一个奇怪的API,你应该改变它,如果你能接受一个数组。 如果你不能,你可以尝试创建和匿名类型,所以你会有类似的东西:
public object GetSerializationObjectForKid(Kid kid)
{
return new
{
age = kid.age,
name = kid.name,
toy_1 = toys.ElementAtOrDefault(0),
toy_2 = toys.ElementAtOrDefault(1),
toy_3 = toys.ElementAtOrDefault(2)
}
}
您可以序列化这个新的匿名对象。
答案 2 :(得分:0)
以下是使用Anonymous Type选择成员并为其命名以符合api要求的示例。它目前假设总会有3&#34;玩具&#34;。
using System.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Web.Script.Serialization;
namespace CommandLineProgram
{
public class DefaultProgram
{
public static void Main()
{
var kid1 = new kid()
{
age = 10,
name = "Jane",
toys = new List<String>
{
"one",
"two",
"three"
}
};
var asdf = new
{
age = kid1.age,
name = kid1.name,
toy_1 = kid1.toys[0],
toy_2 = kid1.toys[1],
toy_3 = kid1.toys[2]
};
JavaScriptSerializer ser = new JavaScriptSerializer();
String serialized = ser.Serialize(asdf);
Console.WriteLine(serialized);
}
}
public class kid
{
public int age;
public String name;
public List<String> toys;
}
}
生成此输出
{
"age" : 10,
"name" : "Jane",
"toy_1" : "one",
"toy_2" : "two",
"toy_3" : "three"
}
答案 3 :(得分:0)
您可以构建一个动态对象,添加所需的属性,然后将其序列化
dynamic jsonData = new System.Dynamic.ExpandoObject();
jsonData.age = kid.age;
jsonData.name = kid.name;
for (int i = 0; i < kid.toys.Count; i++)
{
((IDictionary<String, Object>)jsonData).Add(string.Format("toy_{0}", i), kid.toys[i]);
}