C # Json serialization list

I have a little problem with .Net Json serialization I have a class with a list of strings and I need to serialize it as an 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"  
}

      

this is because of the api. Is there a way how to do this?

+3


source to share


5 answers


Here's a dynamic solution that doesn't involve a 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();
            }
        }
    }

      

using:



    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 an extension you can find here: How to create a 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);
        }
    }
}

      

+3


source


As dcastro says, this is a weird API and you should change it if you can accept an array. If you cannot try to create an anonymous type as well, then you will have something like this:

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.

+1


source


Following is an example of using Anonymous Type to select members and provide names to them as required by the api. It is currently assumed that there will always be 3 "toys".

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

      

Produces this output

{
  "age" : 10,
  "name" : "Jane",
  "toy_1" : "one",
  "toy_2" : "two",
  "toy_3" : "three"
}

      

0


source


I found a solution ... it is not clear, but it works

                JObject data = JObject.Parse(JsonConvert.SerializeObject(exportAuc));

                int i = 0;
                foreach(String file in exportAuc.pdf_ostatni){
                    data.Add("pdf_ostatni_" + i.ToString(), file);
                    i++;
                }
                String output = data.ToString();

      

0


source


You can create a dynamic object adding the properties you want and then serialize it

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

      

0


source







All Articles