Reputation: 99
Does anyone know how to convert a string which contains json that has no parameter names into a C# array. My code receives json from RESTApi That looks like this
[["name","surname","street","phone"],
["alex","smith","sky blue way","07747233279"],
["john","patterson","richmond street","07658995465"]]
Every example I have seen here involved parameter names and their json looked like this
[Name:"alex",Surname:"smith",street:"sky blue way",phone:"07747233279"],
[Name:"john",Surname:"patterson",street:"richmond street",phone:"07658995465"]]
I am trying to use JavaScriptSerializer but i don't know how to properly maintain a Class for such type of JSON
Upvotes: 1
Views: 901
Reputation: 18014
This is not quite what the OP is asking (2d array), but my approach to this problem.
It seems that you have a collection of people, so I'd create a Person class like this:
public class Person
{
public string Name { get; set; }
public string Surname { get; set; }
public string Street { get; set; }
public string Phone { get; set; }
}
And then a parser class that takes the json string as a parameter, and returns a collection of Person:
public class PersonParser
{
public IEnumerable<Person> Parse(string content)
{
if (content == null)
{
throw new ArgumentNullException(nameof(content));
}
if (string.IsNullOrWhiteSpace(content))
{
yield break;
}
// skip 1st array, which contains the property names
var values = JsonConvert.DeserializeObject<string[][]>(content).Skip(1);
foreach (string[] properties in values)
{
if (properties.Length != 4)
{
// ignore line? thrown exception?
// ...
continue;
}
var person = new Person
{
Name = properties[0],
Surname = properties[1],
Street = properties[2],
Phone = properties[3]
};
yield return person;
}
}
}
Using the code:
string weirdJson = @"[[""name"",""surname"",""street"",""phone""],
[""alex"",""smith"",""sky blue way"",""07747233279""],
[""john"",""patterson"",""richmond street"",""07658995465""]]";
var parser = new PersonParser();
IEnumerable<Person> people = parser.Parse(weirdJson);
foreach (Person person in people)
{
Console.WriteLine($"{person.Name} {person.Surname}");
}
Upvotes: 1
Reputation: 81503
You could do this, which will give you a list of list of string
var input = "[[\"name\", \"surname\", \"street\", \"phone\"],\r\n\t[\"alex\", \"smith\", \"sky blue way\", \"07747233279\"],\r\n\t[\"john\", \"patterson\", \"richmond street\", \"07658995465\"]]";
var results = JsonConvert.DeserializeObject<List<List<string>>>(input);
foreach (var item in results)
Console.WriteLine(string.Join(", ", item));
Output
name, surname, street, phone
alex, smith, sky blue way, 07747233279
john, patterson, richmond street, 07658995465
Upvotes: 1