简体   繁体   中英

C# Json serializing List

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.

Here is an example of using an Anonymous Type to select members and give them names to match an api's requirements. It currently assumes 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"
}

I ve found solution...it' s 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();

You can build a dynamic object adding the properties you need 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]);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM