【问题标题】:Remove white spaces in Json Properties in C# [duplicate]删除 C# 中 Json 属性中的空格 [重复]
【发布时间】:2021-09-03 09:20:24
【问题描述】:

我有一个从 API 获取的 json 数据,如下所示。 { “位置代码”:“0000”, “主图像”:“MainImage124”, “英雄形象”:“英雄形象2344”, “城市”:“城市 1” }

我有一个像下面这样的模型类

`public class Class1 {
     public string LocationCode  { get; set; }
     public string MainImage { get; set; }
     public string HeroImage { get; set; }
     public string City { get; set; }
}`

我正在使用 Newtonsoft.Json 反序列化 api 数据。但我缺少 LocationCode、MainImage 和 HeroImage 的数据。我可以看到 City 的数据。我猜这是 json 数据中属性“位置代码”中的空格。

如何去除 Json 属性中的空格(在本例中属性名称为“位置代码”)。
请给我建议。

或者反序列化后LocationCode、MainImage和HeroImage的数据丢失有什么原因吗?

【问题讨论】:

  • 为什么不直接指定属性名称? [JsonProperty("Location Code")] 等?见this question

标签: c# json


【解决方案1】:

String.Trim 方法

您可以在 c# 中使用 String.Trim() 来删除字符串中的空格。

YourProperty.Trim();

返回一个新字符串,其中删除了当前字符串中出现的一组指定字符的所有前导和尾随。

你的情况

LocationCode.Trim();

【讨论】:

  • 这对 OP 有什么帮助?
【解决方案2】:

改为使用 JSON 名称注释您的属性

using Newtonsoft.Json;

 public class Class1 
 {
     [JsonProperty("Location Code")]
     public string LocationCode { get; set; }
     [JsonProperty("Main Image")]
     public string MainImage { get; set; }
     [JsonProperty("Hero Image")]
     public string HeroImage { get; set; }
     public string City { get; set; }
 }

【讨论】:

    猜你喜欢
    • 2017-10-27
    • 2010-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 2019-03-11
    • 2020-04-02
    相关资源
    最近更新 更多