简体   繁体   English

C#Json序列化列表

[英]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: 我有一个小问题.Net Json序列化我有类的字符串列表我需要将它序列化为属性,例如:

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. 这是因为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# 它使用您可以在此处找到的扩展: 如何在C#中创建JSON字符串

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. 正如dcastro所说,这是一个奇怪的API,你应该改变它,如果你能接受一个数组。 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. 下面是使用匿名类型选择成员并为其命名以匹配api要求的示例。 It currently assumes that there will always be 3 "toys". 它目前假设总会有3个“玩具”。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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