-1

I have a City_State list:

City_State[0].Range="\"city\":\"REDMOND\",\"state\":\"AK\"";
City_State[1].Range="\"city\":\"Alex City\",\"state\":\"

How to convert it into json like below:

var _pairs = new
{
    criteria = new { cities = new[] { new { city = "REDMOND", state = "WA" }, 
     new { city = "Alex City", state = "AL" } } 
} ;

I tried the code below, but it does not work:

var _pairs = new { criteria = new { cities = new[] { _paged_City_State.ToArray() } }  };
halfer
  • 19,824
  • 17
  • 99
  • 186
Donald
  • 551
  • 2
  • 6
  • 22
  • If you haven't read this, please do. https://stackoverflow.com/questions/16921652/how-to-write-a-json-file-in-c – O. Jones Feb 06 '19 at 12:24
  • 1
    "json like below:"...but what you have put below is not JSON, it's C#. It does seem like the "Range" property within each item in your City_State array (wherever that comes from) contains something which looks like a partial, escaped bit of JSON. But due to its incompleteness and the escaping, you won't be able to parse it easily. You really need to clarify to us what data you are using and what you want the end result to be. "Does not work" is not enough information for us to help you. Please be clear and _specific_ about your problem, including any error messages and unexpected output. – ADyson Feb 06 '19 at 12:24
  • 1
    The text within the range property is not a valid json. It is missing the curly braces at the beginning and the end. – Oliver Feb 06 '19 at 12:25
  • I want to convert City_State array values into cities – Donald Feb 06 '19 at 12:34
  • Also your title and your texts are telling on how to come from C# classes to JSON, but your code examples are showing more about how to come from JSON to C#. So please be more concise about what is your concrete input (a class with some filled property values or a json string) and what should be the desired output (a class with filled properties or a json string) – Oliver Feb 06 '19 at 12:40

1 Answers1

0

If you had these classes:

public class CityStateRaw
{
    public string Range { get; set; }
}

public class CityState
{
    public string City { get; set; }
    public string State { get; set; }
}

The following code would work:

var ranges = new[]
{
    new CityStateRaw { Range = "{\"city\":\"REDMOND\",\"state\":\"AK\"}" },
    new CityStateRaw { Range = "{\"city\":\"Alex City\",\"state\":\"foo\"}" },
};

var list = ranges
    .Select(raw => JsonConvert.DeserializeObject<CityState>(raw.Range))
    .ToList();

But if this doesn't match your expectations you should be more concrete about what your exact input and the expected output should be.

Oliver
  • 43,366
  • 8
  • 94
  • 151