invalidusername invalidusername - 1 year ago 53
C# Question

parse two-dimensional array string to .net

i'm retrieving the following data from the Census API in string format.

[["NAME","B01001_001E","state","county","tract","block group"],
["Block Group 1, Census Tract 1.10, Franklin County, Ohio","1165","39","049","000110","1"],
["Block Group 2, Census Tract 1.10, Franklin County, Ohio","1038","39","049","000110","2"],
["Block Group 3, Census Tract 1.10, Franklin County, Ohio","551","39","049","000110","3"],
["Block Group 4, Census Tract 1.10, Franklin County, Ohio","881","39","049","000110","4"]]


What would you consider is the best way to parse this data into a List or perhaps even an DataTable where we use the column names?

I'm now writing my own parser, (using split, etc.) but I'm hoping there is an easier way that directly parses the data for you. A JSON serializer won't work as it isn't json data (no key, value pairs).

Thanks!

Answer Source

You can just use Json.NET (After all, it's valid JSON):

First, create a class that will represent your entities:

public class Entity
{
    public string Name { get; set; }
    public int B01001_001E { get; set; }
    public int State { get; set; }
    public int County { get; set; }
    public int Tract { get; set; }
    public int BlockGroup { get; set; }
}

Then, deserialize your data:

IEnumerable<string[]> records = JsonConvert.DeserializeObject<IEnumerable<string[]>>(data);

IEnumerable<Entity> entities = 
records.Skip(1) // We skip the header row
.Select(r => new Entity()
{
    Name = r[0],
    B01001_001E = Convert.ToInt32(r[1]),
    State = Convert.ToInt32(r[2]),
    County = Convert.ToInt32(r[3]),
    Tract = Convert.ToInt32(r[4]),
    BlockGroup = Convert.ToInt32(r[5])
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download