简体   繁体   English

将json数组保存到c#类对象

[英]Saving json array to c# class object

I have to assign json array of string to ac# class.我必须将 json 字符串数组分配给 ac# 类。 I have done like below.我做了如下。 But I got an exceptio但我有一个例外

Cannot deserialize the current JSON array (eg [1,2,3]) into type 'LoggedInUserDetails' because the type requires a JSON object (eg {\\"name\\":\\"value\\"}) to deserialize correctly.\\r\\nTo fix this error either change the JSON to a JSON object (eg {\\"name\\":\\"value\\"}) or change the deserialized type to an array or a type that implements a collection interface (eg ICollection, IList) like List that can be deserialized from a JSON array.无法将当前 JSON 数组(例如 [1,2,3])反序列化为“LoggedInUserDetails”类型,因为该类型需要 JSON 对象(例如 {\\"name\\":\\"value\\"})才能正确反序列化。\\r \\n要修复此错误,请将 JSON 更改为 JSON 对象(例如 {\\"name\\":\\"value\\"})或将反序列化类型更改为数组或实现集合接口的类型(例如 ICollection、IList ) 像可以从 JSON 数组反序列化的 List。 JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.\\r\\nPath '', line 1, position 1."}还可以将 JsonArrayAttribute 添加到类型以强制它从 JSON 数组反序列化。\\r\\n路径 '',第 1 行,位置 1。"}

public class LoggedInUserDetails
{
    public string login_user_name
    {
        get; set;
    }

    public string login_user_id
    {
        get; set;
    }
}

 var GetResponse = await response2.Content.ReadAsStringAsync();
//"[{\"login_user_name\":\"Rahul\",\"login_user_id\":\"43\"}]"
 LoggedInUserDetails obj = JsonConvert.DeserializeObject<LoggedInUserDetails>(GetResponse);
 Variables.login_user_name = obj.login_user_name;
 Variables.login_user_id= obj.login_user_id;

You should deserialize the json string to an IEnumerable collection or Array .您应该deserialize json字符串deserialize IEnumerable集合或Array

 var content = await response2.Content.ReadAsStringAsync();
 var result = JsonConvert.DeserializeObject<List<LoggedInUserDetails>>(content);

It because of the '[]', which stores it as a array of results.这是因为 '[]' 将其存储为结果数组。 You should be able to do something like the following:您应该能够执行以下操作:

LoggedInUserDetails obj = JsonConvert.DeserializeObject<List<LoggedInUserDetails>>(GetResponse);

where you try to deserialize object as an list.您尝试将对象反序列化为列表的地方。 The list will only contain 1 object.该列表将仅包含 1 个对象。

full example:完整示例:

public class LoggedInUserDetails
{
    public string login_user_name
    {
        get; set;
    }

    public string login_user_id
    {
        get; set;
    }
}

 var GetResponse = await response2.Content.ReadAsStringAsync();
//"[{\"login_user_name\":\"Rahul\",\"login_user_id\":\"43\"}]"
 List<LoggedInUserDetails> obj = JsonConvert.DeserializeObject<List<LoggedInUserDetails>>(GetResponse);
 Variables.login_user_name = obj[0].login_user_name;
 Variables.login_user_id= obj[0].login_user_id;

This way:这边走:

LoggedInUserDetails obj = JsonConvert.DeserializeObject<LoggedInUserDetails[]>(GetResponse).FirstOrDefault() ?? throw new Exception("User not found.");
Variables.login_user_name = obj.login_user_name;
Variables.login_user_id = obj.login_user_id;

Your result was an array containing 1 object, so you just had to convert it to an array of your desired object and take the first.您的结果是一个包含 1 个对象的数组,因此您只需将其转换为所需对象的数组并取第一个。

Since you are using array, then it should deserialize array to list public class Test { public string login_user_name {get;由于您使用的是数组,那么它应该反序列化数组以列出 public class Test { public string login_user_name {get; set;} public string login_user_id { get;设置;} 公共字符串 login_user_id { 获取; set;} }放;} }

string js =  "[{\"login_user_name\":\"Rahul\",\"login_user_id\":\"43\"}]";
var result  =  JsonConvert.DeserializeObject<List<Test>>(js);
foreach(var ob in result)
{
  Console.WriteLine(ob.login_user_name);
  Console.WriteLine(ob.login_user_id);
}

output输出

Rahul
43

保存数组的问题<object>在后端 C# 列表中<object><div id="text_translate"><p>我有表格内的表格和网格外的其他字段的表格,并尝试将所有这些数据保存到 SQL 服务器数据库中,但是当我尝试 Axios 时没有连接到后端服务。 我认为问题在于 Array 与 List 的兼容性。 我不知道做事的正确方法。 打字稿 Model 是:</p><pre> import { RepairDetModel } from '../../models/repairDet/repairDetModel'; export class RepairMasterModel { public repairMasterId: number; public autoUserId: number; public year: string; public repairDetails: Array&lt;RepairDetModel&gt;; public isActive: boolean; }</pre><p> Axios 请求</p><pre>add(repairMaster: RepairMasterModel) { return axios({ url: `repairMaster/create`, method: 'post', headers: { "Content-Type": "application/json; charset=utf-8" }, data: JSON.stringify(repairMaster) }).then(res =&gt; res.data.data).catch(error =&gt; Promise.reject(HelperFunctions.getErrorMessage(error)) ) }</pre><p> 和后端服务</p><pre>public int Create(RepairMasterDTO repairDTO) { try { if (string.IsNullOrEmpty(repairDTO.Year)) throw new BusinessValidationException(ErrorCodes.REPAIRMASTER_YEAR_MISSING); var repairEntity = new RepairMasterEntity() { AutoUserId = repairDTO.AutoUserId, Year = repairDTO.Year, IsActive = repairDTO.IsActive, UpdatedOn = DateTime.Now, }; int repairId = DataAccessService.RepairMasterRepository.Create(repairEntity); DataAccessService.Commit(); return repairId; } catch (Exception ex) { throw ex; } }</pre><p> 维修MasterDTO class</p><pre> public class RepairMasterDTO { public int RepairMasterId { get; set; } public string Year { get; set; } public int AutoUserId { get; set; } public List&lt;RepairDetDTO&gt; RepairDetails { get; set; } public bool IsActive { get; set; } }</pre></div></object></object> - Problem saving array<object> in backend C# list<object>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C#保存对象列表与保存对象(来自JSON) - C# Saving Object List Vs Saving Object (From JSON) 将JSON数据保存到C#自定义对象中 - Saving JSON data into a C# custom object Map JSON object to C# class property array - Map JSON object to C# class property array 将JSON数组对象反序列化为C#类类型转换 - Deserialize JSON array Object to c# class type conversion C#JSON到对象(或数组) - C# JSON to object (or array) 具有空json数组的C#json对象 - C# json object with empty json array 在c#中删除Json数组中的Json对象 - Remove Json Object in Json Array in c# 在C#中将JSON ARRAY转换为JSON对象 - JSON ARRAY to JSON Object in c# 将 json 数组反序列化为 object 为 c# object - deserializing json array into object into c# object 保存数组的问题<object>在后端 C# 列表中<object><div id="text_translate"><p>我有表格内的表格和网格外的其他字段的表格,并尝试将所有这些数据保存到 SQL 服务器数据库中,但是当我尝试 Axios 时没有连接到后端服务。 我认为问题在于 Array 与 List 的兼容性。 我不知道做事的正确方法。 打字稿 Model 是:</p><pre> import { RepairDetModel } from '../../models/repairDet/repairDetModel'; export class RepairMasterModel { public repairMasterId: number; public autoUserId: number; public year: string; public repairDetails: Array&lt;RepairDetModel&gt;; public isActive: boolean; }</pre><p> Axios 请求</p><pre>add(repairMaster: RepairMasterModel) { return axios({ url: `repairMaster/create`, method: 'post', headers: { "Content-Type": "application/json; charset=utf-8" }, data: JSON.stringify(repairMaster) }).then(res =&gt; res.data.data).catch(error =&gt; Promise.reject(HelperFunctions.getErrorMessage(error)) ) }</pre><p> 和后端服务</p><pre>public int Create(RepairMasterDTO repairDTO) { try { if (string.IsNullOrEmpty(repairDTO.Year)) throw new BusinessValidationException(ErrorCodes.REPAIRMASTER_YEAR_MISSING); var repairEntity = new RepairMasterEntity() { AutoUserId = repairDTO.AutoUserId, Year = repairDTO.Year, IsActive = repairDTO.IsActive, UpdatedOn = DateTime.Now, }; int repairId = DataAccessService.RepairMasterRepository.Create(repairEntity); DataAccessService.Commit(); return repairId; } catch (Exception ex) { throw ex; } }</pre><p> 维修MasterDTO class</p><pre> public class RepairMasterDTO { public int RepairMasterId { get; set; } public string Year { get; set; } public int AutoUserId { get; set; } public List&lt;RepairDetDTO&gt; RepairDetails { get; set; } public bool IsActive { get; set; } }</pre></div></object></object> - Problem saving array<object> in backend C# list<object>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM