如何在C#中将类对象转换为json数组? [英] How to convert class object to json array in C#?
问题描述
我通过winform调用web api,当我将数据传递给类并调用函数时,它向我显示错误。
无法将当前JSON对象(例如{name:value})反序列化为类型Properties.Model.Tenant.TenantListItem [],因为该类型需要JSON数组(例如[ 1,2,3])正确反序列化。
我尝试过:
[DataContract]
public class TenantFilter
{
[DataMember]
public string TenantName { get ; set ; }
[DataMember]
public long AreaID {获得跨度>; set ; }
}
// 我的网络API代码
public async 任务< list>< tenantlistitem>> GetAllTenant(TenantFilter过滤器)
{
var result = new 列表< tenantlistitem> ();
尝试
{
var response = await TenantCore.LoadTenantGrid(filter);
if (response!= null )
{
result = (列表与LT; tenantlistitem>)响应;
}
}
catch (System.Exception ex)
{
}
返回结果;
}
// 通过winform调用
private async 任务< ienumerable>< tenantlistitem>> PopulateTenantGridView()
{
var result = new 列表< tenantlistitem>() ;
尝试
{
使用( var client = new HttpClient())
{
var name = txtName.Text;
var area =(cmbArea.SelectedValue == null ? 0 :( long )cmbArea.SelectedValue);
var tenantfilter = new TenantFilter
{
TenantName = name,
AreaID = area
};
var serializedProduct = JsonConvert.SerializeObject(tenantfilter,Formatting.Indented);
var content = new StringContent(serializedProduct,Encoding.UTF8, application / json);
var response = await client.PostAsync( http:// localhost:64456 / api / Tenant / GetAllTenant /,content);
if (response.IsSuccessStatusCode)
{
var Jsonstring = await response.Content.ReadAsStringAsync();
var tenant = JsonConvert.DeserializeObject< tenantlistitem [] > (Jsonstring).ToList( );
如果(租户!= null )
{
result = tenant.Take( 100 )。ToList();
}
}
}
}
catch (例外情况)
{
MessageBox.Show(ex.Message);
}
返回结果;
}
那是因为,你的JSON可能只是这样,
< pre lang =c#> { / * 此处的文档数据。 * / }
但是,您执行的代码要求您的JSON文档包含对象数组,以<$ c开头$ c> [并以结尾]
。这是您遇到的错误。更新服务器上的JSON文档,以便您的客户端代码可以正常工作。如果这不起作用,那么你必须自己使用try ... catch
块来解决问题。
阅读我写的以下文章以及我之前的一些答案,这些文章将帮助您更好地理解这个概念:
使用C#从JSON中的零到英雄 [ ^ ]
http://www.codeproject.com/Answers/1109587/How-to-deserialize-my-json-data-to-relevent-object#answer1 [ ^ ]
http ://www.codeproject.com/Answers/836988/how-to-remove-d uplicate-a-json-file#answer2 [ ^ ]
http://www.codeproject.com/Answers/879055/How-do-I-get-Ajax-to -read-my-json-string#answer1 [ ^ ]
http://www.codeproject.com/Answers/828795/How-do-I-write-a- Csharp-program-to-read-json-data#answer2 [ ^ ]
VAR 跨度> tenantfilter = new TenantFilter
{
TenantName = name,
AreaID = area
};
var serializedProduct = JsonConvert.SerializeObject(tenantfilter,Formatting.Indented);
此序列化为1个对象{name:value}您可以将代码更改为:
var tenantfilter = new TenantFilter
{
TenantName = name,
AreaID = area
};
var tenantFilterList = new List< tenantfilter>();
tenantFilterList.Add(tenantFilter);
var serializedProduct = JsonConvert.SerializeObject(tenantfilterList,Formatting.Indented);
这序列化为包含1个对象[{name:value}]的数组...注意[]差异表示数组
如果你向列表添加更多对象那么它将是序列化,如[{name:value},{name:value2},... etc]
在使用Get方法的立场我正在使用Post在Web api然后我修复了问题。
以下是我的代码
[HttpPost]
[Route(PopulateTenantGrid)]
public async 任务< list>< tenantlistitem>> GetAllTenant(TenantFilter过滤器)
{
var result = new 列表< tenantlistitem> ();
尝试
{
var response = await TenantCore.LoadTenantGrid(filter);
if (response!= null )
{
result = (列表与LT; tenantlistitem>)响应;
}
}
catch (System.Exception ex)
{
}
返回结果;
}
i am calling web api through winform when i pass data to the class and call the function its show me the error.
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'Properties.Model.Tenant.TenantListItem[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
What I have tried:
[DataContract]
public class TenantFilter
{
[DataMember]
public string TenantName { get; set; }
[DataMember]
public long AreaID { get; set; }
}
// my web api code
public async Task<list><tenantlistitem>> GetAllTenant(TenantFilter filter)
{
var result = new List<tenantlistitem>();
try
{
var response = await TenantCore.LoadTenantGrid(filter);
if (response != null)
{
result = (List<tenantlistitem>)response;
}
}
catch (System.Exception ex)
{
}
return result;
}
// calling through winform
private async Task<ienumerable><tenantlistitem>> PopulateTenantGridView()
{
var result = new List<tenantlistitem>();
try
{
using (var client = new HttpClient())
{
var name = txtName.Text;
var area = (cmbArea.SelectedValue == null ? 0 : (long)cmbArea.SelectedValue);
var tenantfilter = new TenantFilter
{
TenantName = name,
AreaID = area
};
var serializedProduct = JsonConvert.SerializeObject(tenantfilter,Formatting.Indented);
var content = new StringContent(serializedProduct, Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://localhost:64456/api/Tenant/GetAllTenant/", content);
if (response.IsSuccessStatusCode)
{
var Jsonstring = await response.Content.ReadAsStringAsync();
var tenant = JsonConvert.DeserializeObject<tenantlistitem[]>(Jsonstring).ToList();
if (tenant != null)
{
result = tenant.Take(100).ToList();
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return result;
}
That is because, your JSON might be only like this,
{ /* document data here. */ }
But, the code that you are executing requires that your JSON document to be containing an array of the objects, which starts with[
and ends with]
. That is the error that you are encountering. Update the JSON document on the server so that your client-side code would work. If that doesn't work, then you would have to handle the problem yourself by using atry...catch
block.
Read the following articles that I wrote and a bunch of my previous answers that would help you understand this concept even more:
From zero to hero in JSON with C#[^]
http://www.codeproject.com/Answers/1109587/How-to-deserialize-my-json-data-to-relevent-object#answer1[^]
http://www.codeproject.com/Answers/836988/how-to-remove-duplicate-records-in-a-json-file#answer2[^]
http://www.codeproject.com/Answers/879055/How-do-I-get-Ajax-to-read-my-json-string#answer1[^]
http://www.codeproject.com/Answers/828795/How-do-I-write-a-Csharp-program-to-read-json-data#answer2[^]
var tenantfilter = new TenantFilter { TenantName = name, AreaID = area }; var serializedProduct = JsonConvert.SerializeObject(tenantfilter,Formatting.Indented);
this serializes to 1 object {"name":"value"} You can change the code to:
var tenantfilter = new TenantFilter { TenantName = name, AreaID = area }; var tenantFilterList = new List<tenantfilter>(); tenantFilterList.Add(tenantFilter); var serializedProduct = JsonConvert.SerializeObject(tenantfilterList,Formatting.Indented);
this serializes to array which contains 1 object [ {"name":"value"} ] ...note the [ ] difference which indicates array
if you add more objects to list then it would be serialized such as [ {"name":"value"}, {"name":"value2"}, ...etc]
in stand of using Get Method I am using Post In Web api then i fixed the problem.
below is my code
[HttpPost]
[Route("PopulateTenantGrid")]
public async Task<list><tenantlistitem>> GetAllTenant(TenantFilter filter) { var result = new List<tenantlistitem>(); try { var response = await TenantCore.LoadTenantGrid(filter); if (response != null) { result = (List<tenantlistitem>)response; } } catch (System.Exception ex) { } return result; }
这篇关于如何在C#中将类对象转换为json数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!