I have a little problem with .Net Json serializing I have class withlist of strings an i need to serialize it as attribute for example:
original:
class:
kid{
int age;
String name;
List[String] toys;
}
result:
{
"age":10,
"name": Jane,
"toys":["one", "two", "three"]
}
i need
{
"age":10,
"name": Jane,
"toy_1": "one",
"toy_2": "two",
"toy_3": "three"
}
it's because of api. Is there any way how to do it?
Here's a dynamic solution that does not assume the number of toys:
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();
}
}
}
usage:
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();
}
It uses the extension you can find here: 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);
}
}
}
As dcastro says, it's a weird API, and you should change it if you can to accept an array. If you cannot you can try to create and anonymous type, so you will have something like that:
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)
}
}
Than you can serialize this new anonymous object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With