1

I am looking for a way to convert the following manually typed JSON list to a List I can load, but still output the same format in C#, so in can be POSTed to a REST API.

var accs = @"{
        " + "\n" +
          @"    ""Cities"": [                
        " + "\n" +
          @"        ""Atlanta"",
        " + "\n" +
          @"        ""Chicago"",
        " + "\n" +
          @"        ""San Diego""
        " + "\n" +
          @"    ]
        " + "\n" +
          @"}
        " + "\n" +
          @"";
  • 3
    I think first you need to find out who manually typed this code and have some harsh words with them – Jonesopolis Jun 21 '22 at 16:51
  • @Jonesopolis This is not a nice comment. Maybe he is new to C# and showed us how he initially handled the problem and tries to find a clean solution. – ˈvɔlə Jun 21 '22 at 17:49
  • When you use `@"`, you can avoid the `+` concatenation and just put your JSON on multiple lines. Use `'` instead of `"` in your JSON text. – nullforce Jun 21 '22 at 17:58
  • @ˈvɔlə I'm sorry - I didn't mean for it to be anything but satirical. We (especially me) are all guilty of writing questionable code. I see people on this site get way too serious sometimes and it's nice to be able to have a quick laugh – Jonesopolis Jun 21 '22 at 18:04

3 Answers3

0

Assuming this is your model:

public class State
    {
        public List<string> Cities { get; set; }

        public State(List<string> cities)
        {
            Cities = cities;
        }
    }

This is how you serialize and deserialize:

using System.Text.Json;

var listOfCities = new List<string>() { "Atlanta", "Chicago", "San Diego"};

var state = new State(listOfCities);

//Serialize
var jsonArray = JsonSerializer.Serialize(state);

// Deserialize
var obj = JsonSerializer.Deserialize<State>(jsonArray); 
Liad
  • 336
  • 5
  • 15
0

When you use @", you can avoid the + concatenation like:

var accs = @"
{
  'Cities': [
    'Atlanta',
    'Chicago',
    'San Diego'
  ]
}
";

You'll need to use ' (single quotes) instead of " in your JSON text, otherwise you have to escape \" them.

nullforce
  • 1,051
  • 1
  • 8
  • 13
0

you don't need any custom classes, you can just parse your json string

using Newtonsoft.Json;

 var jsonParsed=JObject.Parse(accs);

if you need list of cities as c# instance

 List<string> cities =jsonParsed["Cities"].ToObject<List<string>>();

if you need just a well formatted json string

 accs = jsonParsed.ToString();

result

{
  "Cities": [
    "Atlanta",
    "Chicago",
    "San Diego"
  ]
}
Serge
  • 40,935
  • 4
  • 18
  • 45