0

Is there a way to generate Serialized string of List <object> without any [ ]

we are doing serialization using following code

JsonConvert.SerializeObject(data)

[
  {
    "SessionId": "6d1ea52b-9f0c-4c32-835d-49e6db22efee",
    "ComponentName": "WebRole",
    "Message": "X"
  },
  {
    "SessionId": "6d1ea52b-9f0c-4c32-835d-49e6db22efee",
    "ComponentName": "WebRole",
    "Message": "Y"
  },
  {
    "SessionId": "6d1ea52b-9f0c-4c32-835d-49e6db22efee",
    "ComponentName": "WebRole",
    "Message": "Z"
  },
  {
    "SessionId": "6d1ea52b-9f0c-4c32-835d-49e6db22efee",
    "ComponentName": "WebRole",
    "Message": "XY"
  },
  {
    "SessionId": "6d1ea52b-9f0c-4c32-835d-49e6db22efee",
    "ComponentName": "WebRole",
    "Message": "XYZ",
    "Payload": "X>>1"
  }
]

Is there a way to remove above [ and ] , I have workaround to call Trim('[') and Trim(']') on serialize string. Is there any setting that come out of box from NewtonSoft which removes [ and ], also I dont want to make use of anonymous object.

5
  • 1, 2, 3, 4 numbers after SessionId property are typos or they are present in your data ? Commented Mar 21, 2019 at 9:48
  • 3
    If you remove square brackets [] then your resultant JSON would be invalid. You can copy and paste your output json check here json2csharp.com Commented Mar 21, 2019 at 9:51
  • we will not use deserialize function in C#. Instead, we will be ingesting data using some tool to insert into SQL/Data Store etc. Commented Mar 21, 2019 at 9:53
  • you would use Substring like => var newStr = jsonStr.Substring(1, jsonStr.Length - 1); Commented Mar 21, 2019 at 9:56
  • If you tell newtonsoft to remove square brackets from json then It replies you that I am being programmed to produce only valid JSON, so how can I give you invalid JSON? So my suggestion is to go with string manipulation by using Trim or Substring Commented Mar 21, 2019 at 10:09

2 Answers 2

1

No there's no way, if data is a collection then JsonConvert will return a JSON array. You can as you stated modify the output string by using Trim('[').Trim(']') but your JSON won't be valid.

Sign up to request clarification or add additional context in comments.

2 Comments

You should add suggestions as comment
@Sunil the question was "Is there a way to remove above ... ?" and my answer was no, I edit my answer to be more specific.
0

You're trying to use a List, not a Map/Dictionary, but you don't want the array behavior that comes with a List (but not a Dictionary/Map).

Get these straight and you'll find data MUCH easier to work with in many programming languages ;)

https://stackoverflow.com/a/4131714/901899

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.