序列化为不带属性名的json

时间:2019-03-16 16:45:13

标签: c# json

我需要使用Newtonsoft JSON序列化对象,并提供所需的输出:

[  
   [[1, 2, "15"],[3, 4, "12"]]
]

我的课:

 public class Result
 {
  public int? score1;  
  public int? score2;    
  public string id;
 }

Id必须为字符串类型。转换为JSON后:

string json = JsonConvert.SerializeObject(myObject);

我,从逻辑上讲,是这样的:

[  
   [  
      {  
         "score1":null,
         "score2":null,
         "id":"5824"
      },
      {  
         "score1":null,
         "score2":null,
         "id":"5825"
      }
   ],
   [next object]
]

1 个答案:

答案 0 :(得分:1)

您可以尝试使用JProperties.Values()方法来提取值并最终使用JSON.NET将其序列化:


public class Program
{
    public static void Main(string[] args)
    {
        List<Result> resultList = new List<Result>
        {
            new Result 
            {
                score1 = 1,
                score2 = 2,
                id = "15"
            },
            new Result
            {
                score1 = 3,
                score2 = 4,
                id = "12"
            }
        };




        var valuesList = JArray.FromObject(resultList).Select(x => x.Values().ToList()).ToList();

        string finalRes = JsonConvert.SerializeObject(valuesList, Formatting.Indented);

        Console.WriteLine(finalRes);
    }
}

public class Result
{
     public int? score1 {get; set; }
     public int? score2 { get; set; }   
     public string id { get; set; }
}

给出结果:

[
  [
    1,
    2,
    "15"
  ],
  [
    3,
    4,
    "12"
  ]
]