使用Newtonsoft.Json将两个数组转换为一个JSON对象

时间:2015-07-03 23:34:01

标签: c# arrays json json.net

我有数组name[]lastname[]。如何将它们组合并转换为JSON字符串?我希望它采用以下格式。我需要"员工" JSON中的标题。

{ "Employees" : [
    {"name": "John", "lastname": "Coleman"},
    {"name": "Chip", "lastname": "Dale"},
    {"name": "Ann", "lastname": "Smith"},
    {"name": "Terry", "lastname": "Johnson"},
    {"name": "Mary", "lastname": "Loggins"},
    {"name": "Timothy", "lastname": "Lopez"},
    {"name": "Jessica", "lastname": "Brown"}
]}

我需要一种有效的方法来实现这一点,因为数组中有很多项。我实际上有两个以上的数组需要组合成一个JSON对象。为简单起见,我展示了我想要的两个。他们都有相同数量的物品,并订购。我不想迭代数组并自己构造JSON字符串。

更新

我忘了提到我的数组是IEnumerable<[]>字符串和整数数组。这是我尝试在另一个类中创建数组。

  public string[] Name {
                get{ return  (Employees ?? Enumerable.Empty<Employee> ()).Select (p => p.name).ToArray(); }
            }

    public string[] Lastname {
                get{ return  (Employees ?? Enumerable.Empty<Employee> ()).Select (p => p.lastname).ToArray(); }
            }

    public int[] Age {
                get{ return  (Employees ?? Enumerable.Empty<Employee> ()).Select (p => p.age).ToArray(); }
            }

然后我访问它们

var name = X.Select(s => s.Name).ToArray();
var lastname = X.Select(s => s.Lastname).ToArray();
var age = X.Select(s => s.Age).ToArray();

var employees = new { Employees = Enumerable.Range(0, name.Length).Select(i => new { name = name[i], lastname = lastname[i], age = age[i] }) };
var json = JsonConvert.SerializeObject(employees, Formatting.Indented);
Debug.WriteLine(json);

由于某些原因,这会返回类似于

的内容
{"Employees":[{"name":["John","Chip","Ann","Terry"],"lastname":["Coleman","Dale","Smith","Johnson"],"age":[42, 26, 33, 24]}]}

其中所有名称,姓氏都放在一起。我如何获得正确的格式?

1 个答案:

答案 0 :(得分:7)

您可以将它们与Zip()合并为anonymous type,然后将其序列化:

        string[] name = new string[] { "John", "Chip" };
        string[] lastname = new string[] { "Coleman", "Dale" };

        var employees = new { Employees = name.Zip(lastname, (n1, n2) => new { name = n1, lastname = n2 }) };
        var json = JsonConvert.SerializeObject(employees, Formatting.Indented);
        Debug.WriteLine(json);

哪个输出:

{
  "Employees": [
    {
      "name": "John",
      "lastname": "Coleman"
    },
    {
      "name": "Chip",
      "lastname": "Dale"
    }
  ]
}

对于多个数组,使用Enumerable.Range()并行迭代数组可能更容易:

        string[] name = new string[] { "John", "Chip" };
        string[] lastname = new string[] { "Coleman", "Dale" };
        string[] title = new string[] { "Mr", "Dr" };
        string[] profession = new string[] { "Coder", "Doctor" };

        var employees2 = new { Employees = Enumerable.Range(0, name.Length).Select(i => new { title = title[i], name = name[i], lastname = lastname[i], profession = profession[i] }) };
        var json2 = JsonConvert.SerializeObject(employees2, Formatting.Indented);
        Debug.WriteLine(json2);

<强>更新

如果您的字符串位于IEnumerable<String[]>中,则可以将该外部可枚举转换为数组,然后将其编入索引。例如,给出以下测试用例:

        string[] name = new string[] { "John", "Chip" };
        string[] lastname = new string[] { "Coleman", "Dale" };
        string[] title = new string[] { "Mr", "Dr" };
        string[] profession = new string[] { "Coder", "Doctor" };

        IEnumerable<string[]> strings = new[] { title, name, lastname, profession };

你可以这样做:

        var stringArray = strings.ToArray();

        var employees2 = new { Employees = Enumerable.Range(0, name.Length).Select(i => new { title = stringArray[0][i], name = stringArray[1][i], lastname = stringArray[2][i], profession = stringArray[3][i] }) };
        var json2 = JsonConvert.SerializeObject(employees2, Formatting.Indented);
        Debug.WriteLine(json2);

结果是:

{
  "Employees": [
    {
      "title": "Mr",
      "name": "John",
      "lastname": "Coleman",
      "profession": "Coder"
    },
    {
      "title": "Dr",
      "name": "Chip",
      "lastname": "Dale",
      "profession": "Doctor"
    }
  ]
}

更新2

如果您实际拥有包含员工枚举的对象枚举,则可以使用Enumerable.SelectMany展平它们。例如,给定以下类:

public class Employee
{
    public string name { get; set; }
    public string lastname { get; set; }
    public int age { get; set; }
    public string someMoreDataThatShouldNotBeSerialized { get; set; }
}

public class EmployeeContainer
{
    public IEnumerable<Employee> Employees { get; set; }
}

你可以按如下方式展平它们:

        var X = GetAllEmployees();

        var employees = X.SelectMany(s => s.Employees ?? Enumerable.Empty<Employee>()).Select(e => new { name = e.name, lastname = e.lastname, age = e.age });
        var json = JsonConvert.SerializeObject(employees, Formatting.Indented);
        Debug.WriteLine(json);

然后是测试设置

    public static IEnumerable<EmployeeContainer> GetAllEmployees()
    {
        return new[] { 
            new EmployeeContainer { 
                Employees = 
                    new[] { 
                        new Employee { name = "John", lastname = "Coleman", age = 42, someMoreDataThatShouldNotBeSerialized = "someMoreData1" },
                        new Employee { name = "Chip", lastname = "Dale", age = 26, someMoreDataThatShouldNotBeSerialized = "someMoreData2" },
                    } 
            },
            new EmployeeContainer { 
                Employees = 
                    new[] { 
                        new Employee { name = "Ann", lastname = "Smith", age = 33, someMoreDataThatShouldNotBeSerialized = "someMoreData3" },
                        new Employee { name = "Terry", lastname = "Johnson", age = 24, someMoreDataThatShouldNotBeSerialized = "someMoreData4" }, 
                    } 
            },
            new EmployeeContainer()
        };
    }

产地:

[
  {
    "name": "John",
    "lastname": "Coleman",
    "age": 42
  },
  {
    "name": "Chip",
    "lastname": "Dale",
    "age": 26
  },
  {
    "name": "Ann",
    "lastname": "Smith",
    "age": 33
  },
  {
    "name": "Terry",
    "lastname": "Johnson",
    "age": 24
  }
]

工作fiddle