【问题标题】:How to write the value of one json property in one line?如何在一行中写入一个json属性的值?
【发布时间】:2019-08-19 01:27:46
【问题描述】:

必须在 json 中写入“坐标”属性的值,而不需要为以下几行加上连字符,而不是使用 ToString()(不将值转换为字符串)。想要的结果如下所示。

{
          "Id": null,
          "Style": "1234",
          "Geometry": {
            "Type": "Polygon",
            "Coordinates": [[[47541.470259278358,6846.8710054924586],[47540.359922950891,6845.4552435801925],[47541.470259278358,6846.8710054924586]]],
            "Properties": [
              {
                "PointType": "Straight"
              },
              {
                "PointType": "Straight"
              },
              {
                "PointType": "Straight"
              }
            ]
       }
}

但不是:

{
          "Id": null,
          "Style": "1234",
          "Geometry": {
            "Type": "Polygon",
            "Coordinates": "[[[47541.470259278358,6846.8710054924586],[47540.359922950891,6845.4552435801925],[47541.470259278358,6846.8710054924586]]]",
            "Properties": [
              {
                "PointType": "Straight"
              },
              {
                "PointType": "Straight"
              },
              {
                "PointType": "Straight"
              }
            ]
       }
}

序列化json中对应类对象的函数:

JToken ToJson()
        {
            using (var writer = new JTokenWriter()) {
                JsonSerializer serializer = new JsonSerializer();
                serializer.Serialize(writer, this);
                return writer.Token;
            }
        }

【问题讨论】:

  • “一行”是指一行C#代码还是一行JSON?
  • 一行JSON
  • 请提供几行代码并告诉我们您使用哪个解析器进行序列化。
  • JSON 中的空格无关紧要,所以无论是嵌套数组打印一行还是多行,从解析器/编写器的角度来看,JSON 仍然是相同的 JSON。只需正常编写 JSON 即可。您只需要一种自定义方式来打印您的 JSON。
  • 默认情况下,json 与每个子数组的换行符一起显示,并在以下几行中显示新的单元格。是否可以删除特定属性(“坐标”)的连字符?

标签: c# json jsonparser


【解决方案1】:

您的第二种情况似乎包含 Coordinates 属性作为序列化字符串。

为什么不应该使用 var string = JsonConvert.SerializeObject(YourObject)?

但你应该先安装https://www.nuget.org/packages/Newtonsoft.Json/

你可以对需要双引号的属性使用字符串类型,如果不需要,可以使用数组或数字

【讨论】:

  • 没错。这对我不好。要将属性的值写在一行中,建议将值转换为字符串(如这里stackoverflow.com/questions/570689/…)。但我需要在不将属性值转换为字符串的情况下获得结果。
  • 您的 Coordinates 属性在 c# 类中是如何呈现的?列表>> ?
  • 是的,列表>>
  • JsonConvert.SerializeObject(YourObject) 返回所需的结果,或者我错过了什么?
  • 所以他完全不用换行就写了json。在这种情况下,我将尝试在除“坐标”之外的所有位置添加换行符。
猜你喜欢
  • 2021-05-23
  • 1970-01-01
  • 1970-01-01
  • 2019-10-12
  • 1970-01-01
  • 2013-10-27
  • 1970-01-01
  • 1970-01-01
  • 2022-11-12
相关资源
最近更新 更多