如何在C#中将列表转换为JSON?

时间:2019-02-06 12:03:53

标签: c# json

我有一个City_State列表:

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

如何将其转换为json,如下所示:

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

我尝试了下面的代码,但是它不起作用:

var _pairs = new { criteria = new { cities = new[] { _paged_City_State.ToArray() } }  };

1 个答案:

答案 0 :(得分:0)

如果您有以下课程:

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

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

以下代码将起作用:

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();

但是,如果这与您的期望不符,则应更确切地说明确切的输入和期望的输出。