[英]How do I deserialize a JSON Array containing objects, in C# with Newtonsoft
[
{
"address":"addr1qx8trv7wualsnpj7xt"
},
{
"address":"addr1qxkyl8vvmvy92ngm0y"
},
{
"address":"addr1qywshwl6ud2myc0k2z"
}
]
The above is a JSON file I'm trying to deserialize and read via NewtonsoftJSON.以上是我试图通过 NewtonsoftJSON 反序列化和读取的 JSON 文件。
However, I get the following error但是,我收到以下错误
'Unexpected character encountered while parsing value: {.
'解析值时遇到意外字符:{. Path '', line 1, position 2.'
路径 '',第 1 行,position 2。
What am I doing wrong?我究竟做错了什么? All I want to do is parse all addresses and put them in a list.
我要做的就是解析所有地址并将它们放在一个列表中。
Full Code:完整代码:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
namespace TestJSON
{
class Program
{
static void Main(string[] args)
{
string json = @"[{""address"":""addr1qx8trv7wualsnpj7xt""}, {""address"":""addr1qxkyl8vvmvy92ngm0y""}, {""address"":""addr1qywshwl6ud2myc0k2z""}]";
List<string> addresses = JsonConvert.DeserializeObject<List<string>>(json);
foreach (string address in addresses)
{
Console.WriteLine(address);
}
Console.WriteLine(addresses);
}
}
}
The quick way to do this is to define an anonymous type that has an address
property, then use DeserializeAnonymousType
.快速的方法是定义一个具有
address
属性的匿名类型,然后使用DeserializeAnonymousType
。
string json = @"[{""address"":""addr1qx8trv7wualsnpj7xt""}, {""address"":""addr1qxkyl8vvmvy92ngm0y""}, {""address"":""addr1qywshwl6ud2myc0k2z""}]";
string[] list = JsonConvert.DeserializeAnonymousType(json, new[] { new { address = "" } }).Select(x => x.address).ToArray();
foreach (var item in list) Console.WriteLine(item);
Output: Output:
addr1qx8trv7wualsnpj7xt
addr1qxkyl8vvmvy92ngm0y
addr1qywshwl6ud2myc0k2z
create a class called address that as a string property called address then do创建一个 class 称为地址,作为一个字符串属性称为地址然后做
List<address > addresses = JsonConvert.DeserializeObject<List<address >>(json);
foreach (address a in addresses)
{
Console.WriteLine(a.address );
}
public class address
{
private string _address ="";
// Declare a address property of type string:
public string address
{
get
{
return _address ;
}
set
{
_address = value;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.