【发布时间】:2022-11-13 13:02:58
【问题描述】:
我正在尝试将来自 REST API 的 json 响应转换为 DataTable。以下是我的代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RestSharp;
using Newtonsoft.Json;
using System.Data;
namespace RestDemo1
{
class Program
{
static void Main(string[] args)
{
getEmployeeData();
}
public static void getEmployeeData()
{
var client = new RestClient("https://crmscf.vidyasystems.com/api/gen/items.php");
var request = new RestRequest("items");
var response = client.Execute(request);
string vJ = "";
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
string rawResponse = response.Content;
DataTable tester = (DataTable)JsonConvert.DeserializeObject(rawResponse, (typeof(DataTable)));
}
}
public class Rootobject
{
public int success { get; set; }
public Item[] items { get; set; }
public class Item
{
public string ItemID { get; set; }
public string ItemName { get; set; }
public string ItemDesc { get; set; }
public string MRP { get; set; }
public string Rate { get; set; }
public string Unit { get; set; }
public string Weight { get; set; }
public string ItemGroup { get; set; }
}
}
}
}
当我尝试将数据转换为表格格式时,出现错误:
DataTable tester = (DataTable)JsonConvert.DeserializeObject(rawResponse, (typeof(DataTable)));
错误消息 - Newtonsoft.Json.JsonSerializationException: '读取 DataTable 时出现意外的 JSON 令牌。预期 StartArray,得到 StartObject。路径'',第 1 行,位置 1。
【问题讨论】:
-
调试!在
string rawResponse = response.Content;之后设置断点现在检查json。 -
我能够得到回应。我什至可以使用
dynamic json = JsonConvert.DeserializeObject(rawResponse)反序列化它 -
@SDS 首先将其转换为数组,然后反序列化数组
string[] stringArray = new string[]{ someString }; -
您能与我们分享一个示例 json 吗?
-
错误说明了一切:
Expected StartArray, got StartObject- json 不是应有的数组。