有人知道如何将包含没有参数名称的json的字符串转换为C#数组。我的代码从RESTApi接收到json
[["name","surname","street","phone"],
["alex","smith","sky blue way","07747233279"],
["john","patterson","richmond street","07658995465"]]
我在这里看到的每个示例都涉及参数名称,它们的json看起来像这样
[Name:"alex",Surname:"smith",street:"sky blue way",phone:"07747233279"],
[Name:"john",Surname:"patterson",street:"richmond street",phone:"07658995465"]]
我正在尝试使用JavaScriptSerializer,但我不知道如何为此类JSON正确维护类
答案 0 :(得分:1)
您可以执行此操作,这将为您提供字符串列表的列表
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));
输出
name, surname, street, phone
alex, smith, sky blue way, 07747233279
john, patterson, richmond street, 07658995465
答案 1 :(得分:1)
这并不是OP所要问的(二维数组),而是我对这个问题的解决方法。
似乎您有一群人,所以我要创建一个Person类,如下所示:
public class Person
{
public string Name { get; set; }
public string Surname { get; set; }
public string Street { get; set; }
public string Phone { get; set; }
}
然后是一个解析器类,它将json字符串作为参数,并返回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;
}
}
}
使用代码:
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}");
}