【问题标题】:Serialize to json without property names [duplicate]序列化为没有属性名称的 json [重复]
【发布时间】:2019-03-16 16:45:12
【问题描述】:

我需要用 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]
]

【问题讨论】:

  • 你不说myObject的类型。假设它是Result 的集合,您可以使用ObjectToArrayConverter<Result> 来自C# JSON.NET - Deserialize response that uses an unusual data structure。事实上,我认为这是重复的,同意吗?
  • @dbc 感谢您帮助我,这就像一个魅力。既然你是一个存在一段时间的人,我将把决定权留给你。另一方面,这个问题可能是其他用户的一个很好的入口搜索点。
  • 这个问题对于其他用户来说可能是一个很好的入口搜索点。关闭作为重复并不意味着问题被删除,这意味着重复出现在顶部,而当副本没有答案时,匿名读者将被重定向到原始问题。
  • 感谢您的友好解释。同意。

标签: c# json


【解决方案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"
  ]
]

【讨论】:

  • 感谢 Kunal,我刚刚使用 dbc 建议的方法让它工作,但我很确定这个也不错。接受。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
相关资源
最近更新 更多