3

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?

3
  • 6
    That is one weird API. Commented May 5, 2015 at 13:09
  • You could use an anonymous type, which will let you select each "toy" as a new member. Is the number of toys always the same, or is it variable? Commented May 5, 2015 at 13:22
  • however it's variable. Commented May 5, 2015 at 13:26

5 Answers 5

3

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);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

0

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

1 Comment

I think Paulo's answer is much clearer. Are you using the Json.NET or some other library in this answer, for the JObject and JsonConvert classes?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.