Search code examples
c#jsonjsonparser

How to write the value of one json property in one line?


It is necessary to write value of "Coordinates" property in json without hyphenation for the following lines, not using ToString() (without converting the value to a string). The desired result is shown below.

{
          "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"
              }
            ]
       }
}

but not:

{
          "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"
              }
            ]
       }
}

A function that serializes the corresponding class object in json:

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

Solution

  • it seems your second case contains Coordinates property as serialized string.

    why should not use var string = JsonConvert.SerializeObject(YourObject) ?

    But you should install https://www.nuget.org/packages/Newtonsoft.Json/ first

    You could use string type for properties where you need double quotes and use array or number if you don't need it