gpt4 book ai didi

C# Json序列化List

转载 作者:行者123 更新时间:2023-11-30 15:26:05 28 4
gpt4 key购买 nike

我在 .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。有什么办法吗?

最佳答案

这是一个不假设玩具数量的动态解决方案:

    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);
}
}
}

关于C# Json序列化List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30053909/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com