阅读Json序列化的C# [英] Read Json Serialized c#
问题描述
我正在尝试从此json文本获取ID.我不确定如何获取它不会让我创建一个json对象.我尝试这样做反序列化:
I am trying to get the id from this json text. I'm not sure how to go about getting it doesn't let me create a json object. I tried deserializing it doing this:
public async Task<List<T>> GetIdAsync(string username)
{
var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync(WebServiceURL);
var Id = JsonConvert.DeserializeObject<List<T>>(json);
return Id;
}
但是在反序列化过程中出现此错误
but I get this error during the deserialization
未处理的异常:
Unhandled Exception:
Newtonsoft.Json.JsonReaderException:遇到意外字符 而解析值:{.路径",第1行,位置2
Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: {. Path '', line 1, position 2
这是json文本:
json "[{\"Id\":1,\"FirstName\":\"a\",\"LastName\":\"b\",\"UserName\":\"user\",\"Email\":\"d@gmail.com\",\"Password\":\"poSsUrscOuXL+E5qxXsCsA==\",\"CompanyName\":\"c\",\"Salt\":\"n3ZLSwU9L1g=\",\"Address\":{\"Country\":\"c\",\"Province\":\"p\",\"City\":\"c\",\"PostalCode\":\"p\",\"Street\":\"street\",\"StreetNumber\":\"123\"},\"Telephone\":{\"PersonalPhoneNumber\":\"413414\",\"BusinessPhoneNumber\":\"134134\"},\"Location\":{\"Lat\":45.6025839,\"Lng\":-97.8489959}}]" string
推荐答案
提供作为对象数组的JSON值.您可以使用动态对象仅提取所需的属性.首先将json反序列化为List<dynamic>
,获取列表中的第一个对象,然后调用Id
属性.
Given value of provided JSON which is an array of objects. You can use dynamic object to extract just the property you want. First deserialize the json to a List<dynamic>
, get the first object in the list and call the Id
property.
public async Task<int> GetIdAsync(string username) {
var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync(WebServiceURL);
var list = JsonConvert.DeserializeObject<List<dynamic>>(json);
var obj = list.FirstOrDefault();
int Id = obj != null ? obj.Id : 0;
return Id;
}
更新:
在一个简单的单元测试中对其进行了测试,并通过了预期的测试.
Tested it in a simple unit test and passes as expected.
[TestClass]
public class UnitTest6 {
[TestMethod]
public async Task GetIdAsyncTest() {
var id = await GetIdAsync("");
Assert.IsTrue(id > o);
}
public async Task<int> GetIdAsync(string username) {
var httpClient = new HttpClient();
//simple data just for the purpose of the test.
var json = await Task.FromResult("[{\"Id\":1,\"FirstName\":\"a\"}]"); //await httpClient.GetStringAsync("");
var list = JsonConvert.DeserializeObject<List<dynamic>>(json);
var obj = list.FirstOrDefault();
int Id = obj != null ? obj.Id : 0;
return Id;
}
}
这篇关于阅读Json序列化的C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!