将json转换为列表? [英] Converting json to list ?
本文介绍了将json转换为列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,请告诉我如何将其转换为列表?我鼓励这个错误:
Newtonsoft.Json.Net20.dll发生了一个未处理的Newtonsoft.Json.JsonSerializationException异常例外
附加信息:每次我想反序列化响应时,都无法将JSON对象反序列化为'System.Collections.Generic.List`1 [App_Code.APIResult]'。
。
这是我的回复:
Hi could u please tell me how to convert this to a list? I encourage this error :
An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.Net20.dll
Additional information: Cannot deserialize JSON object into type 'System.Collections.Generic.List`1[App_Code.APIResult]'.
every time I want to deserialize the response.
here is my response:
{"status":"Ok","rows":[{"elements":[{"status":"Ok","duration":{"value":10,"text":""},"distance":{"value":62,"text":"۷۵ متر"}}]}],"origin_addresses":["35.724098,51.424491"],"destination_addresses":["35.724165,51.425121"]}
我尝试过:
What I have tried:
public class APIResult
{
public class Duration
{
public int value { get; set; }
public string text { get; set; }
}
public class Distance
{
public int value { get; set; }
public string text { get; set; }
}
public class Element
{
public string status { get; set; }
public Duration duration { get; set; }
public Distance distance { get; set; }
}
public class Row
{
public IList<Element> elements { get; set; }
}
public class Example //{"status":"Ok", "rows":[ { "elements": [{"status":"Ok", "duration":{"value":11,"text":""}, "distance":{"value":62,"text":"۷۵ متر"}} ]} ], "origin_addresses":["35.724098,51.424491"], "destination_addresses":["35.724165,51.425121"]} }
{
public string status { get; set; }
public IList<Row> rows { get; set; }
public IList<string> origin_addresses { get; set; }
public IList<string> destination_addresses { get; set; }
}
private bool RequestTimeTrip2()
{
if (!mapNRPTTCEventWinService.ReqListInfo(dt_Main))
{
//errLog
return false;
}
string[] arrLatLon = null;
string strResult = string.Empty;
for (int i = 0; i < dt_Main.Rows.Count; i++)
{
arrLatLon = dt_Main.Rows[i]["Points"].ToString().Split('^');
for (int j = 0; j < arrLatLon.Length - 1; j++)
{
var url = "https://api.neshan.org/v1/distance-matrix?origins=" + arrLatLon[j].Split(',')[0] + "," + arrLatLon[j].Split(',')[1] + "&destinations=" + arrLatLon[j + 1].Split(',')[0] + "," + arrLatLon[j + 1].Split(',')[1];
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("Api-Key", "web.dSy4OSDOQtcMokSozr7qmAAvn55jSop5gX95PNTF");
var response = client.GetAsync(url).Result;
List<App_Code.APIResult> objApiResult = new List<APIResult>();
string result = response.Content.ReadAsStringAsync().Result;
// var responseString = new StreamReader(response.Content.ReadAsStreamAsync().Result).ReadToEnd();
StreamReader reader = new StreamReader(result);
result = reader.ReadToEnd();
objApiResult = Newtonsoft.Json.JsonConvert.DeserializeObject<List<APIResult>>(result);
// objApiResult = (App_Code.APIResult)Newtonsoft.Json.JsonConvert.SerializeObject(result);
//List<App_Code.APIResult> lstResult = JsonConvert.DeserializeObject<List<App_Code.APIResult>>(responseString);
// var lobjResult = Newtonsoft.Json.JsonConvert.DeserializeObject<List<APIResult>>(responseString);
//var lobjResult = JsonConvert.DeserializeObject<APIResult>(responseString);
// var deserialized = JsonConvert.DeserializeObject<IEnumerable<App_Code.APIResult>>(response.Content.ReadAsStringAsync().ToString());
// var lobjResult = Newtonsoft.Json.JsonConvert.DeserializeObject<List<APIResult1>>(responseString);
}
}
return true;
}
推荐答案
我的文章中有一个帮助类在C#中使用JSON& VB [ ^ ]我测试了你的类和原始JSON样本进行反序列化并且工作正常。这是我的代码测试:
I have a helper class in my article Working with JSON in C# & VB[^] that I tested your classes and raw JSON sample to be deserialized and works fine. Here is my code test:
class Program
{
static void Main(string[] args)
{
var rawJson = @"{""status"":""Ok"",""rows"":[{""elements"":[{""status"":""Ok"",""duration"":{""value"":10,""text"":""""},""distance"":{""value"":62,""text"":""۷۵ متر""}}]}],""origin_addresses"":[""35.724098,51.424491""],""destination_addresses"":[""35.724165,51.425121""]}";
var result = JsonHelper.ToClass<Example>(rawJson);
}
}
public class Duration
{
public int value { get; set; }
public string text { get; set; }
}
public class Distance
{
public int value { get; set; }
public string text { get; set; }
}
public class Element
{
public string status { get; set; }
public Duration duration { get; set; }
public Distance distance { get; set; }
}
public class Row
{
public IList<Element> elements { get; set; }
}
public class Example
{
public string status { get; set; }
public IList<Row> rows { get; set; }
public IList<string> origin_addresses { get; set; }
public IList<string> destination_addresses { get; set; }
}
public static class JsonHelper
{
public static string FromClass<T>(T data, bool isEmptyToNull = false,
JsonSerializerSettings jsonSettings = null)
{
string response = string.Empty;
if (!EqualityComparer<T>.Default.Equals(data, default(T)))
response = JsonConvert.SerializeObject(data, jsonSettings);
return isEmptyToNull ? (response == "{}" ? "null" : response) : response;
}
public static T ToClass<T>(string data, JsonSerializerSettings jsonSettings = null)
{
var response = default(T);
if (!string.IsNullOrEmpty(data))
response = jsonSettings == null
? JsonConvert.DeserializeObject<T>(data)
: JsonConvert.DeserializeObject<T>(data, jsonSettings);
return response;
}
}
这篇关于将json转换为列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文