【问题标题】:How to efficiently load API results into a DataTable? [duplicate]如何有效地将 API 结果加载到 DataTable 中? [复制]
【发布时间】:2020-05-16 18:28:18
【问题描述】:

API 响应:

{
    "success": true,
    "code": 0,
    "msg": "성공하였습니다.",
    "list": [
        {
            "code": "ANT",
            "code_name": "소둔구분",
            "p_code": "",
            "p_code_name": "",
            "code_type": 0,
            "code_level": 0,
            "max_level": 1,
            "description": "GROP : 99  DETL : ANT  SUBS : 00",
            "create_user": "SYSTEM",
            "create_time": "2019-04-24T17:58:58.000+0000",
            "disable_yn": "Y"
        },
        {...}
        ]
}

C# API 调用:

// CodeInfo 초기 데이터 로드
public static DataTable selectAllCodeInfo()
{
    DataTable dt = new DataTable();
    try
    {
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(API_ADDRESS + "/api/codeInfo");
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = "GET";
        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            JObject applyObj = JObject.Parse(streamReader.ReadToEnd());
            var applyObj2 = streamReader.ReadToEnd();

            string success = applyObj["success"].ToString();

            if (success.Equals("True"))
            {
                if (applyObj["list"].ToString() != null)
                {
                    ??????????
                    return dt;
                }  
            } else
            {
                //API 응답 데이터 수신 실패
            }

        }
    } catch(WebException)
    {
        //API 서버 닫혀있을때, 연결이 안될때
        Console.Write("예외");
        return null;
    }
    catch (Exception)
    {
        //그 외의 Exception
        Console.Write("예외");
        return null;
    }
    return dt;
}

我想有效地将​​上述 API 调用返回数据值加载到 DataTable 中。

我想了几种方法,但还没有找到有效的方法。

我尝试使用 json 数据作为属性对象。 但是太麻烦了,效率低。

在上面的Json数据中,我只想将列表数组中包含的数据加载为DataTable中的列和行。

有什么好的选择吗?

【问题讨论】:

标签: c#


【解决方案1】:

正如Kylethis answerConvert JSON to DataTable 中所解释的,Json.NET(您已经在使用)目前支持将对象列表反序列化为DataTable。在提供的特定 JSON 中,列表嵌入在名为 "list" 的根对象属性中,因此您需要将其提取以反序列化它。

但由于您还询问如何以一种有效的方式执行此操作,因此您将希望避免使用中间表示,例如 streamReader.ReadToEnd()applyObjapplyObj["list"].ToString()。为此,首先引入以下扩展方法,仿照JsonConvert.DeserializeAnonymousType<T>(string value, T anonymousTypeObject)

public static class JsonExtensions
{
    public static T DeserializeAnonymousType<T>(TextReader textReader, T anonymousTypeObject, JsonSerializerSettings settings = null)
    {
        return (T)JsonSerializer.CreateDefault(settings).Deserialize(textReader, typeof(T));
    }
}

现在你可以这样做了:

var root = JsonExtensions.DeserializeAnonymousType(streamReader, 
                                                   new { success = default(bool), list = default(DataTable) });
if (root.success)
{
    var dt = root.list;
    // return the table
}
else
{
    // Handle failure
}

演示小提琴here.

【讨论】:

    【解决方案2】:

    此代码在您的情况下将 json 转换为数据表。Json.NET(您已经在使用)当前支持将对象列表反序列化为数据表。

    public static DataTable selectAllCodeInfo()
    {
        DataTable dt = new DataTable();
        try
        {
             var httpWebRequest = (HttpWebRequest)WebRequest.Create(API_ADDRESS + "/api/codeInfo");
                httpWebRequest.ContentType = "application/json";
                httpWebRequest.Method = "GET";
    
                if (!string.IsNullOrEmpty(RequestParameters))
                    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                    {
                        streamWriter.Write(RequestParameters);
                    }
                var result = string.Empty;
                var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    result = streamReader.ReadToEnd();
                }
            dt = JsonConvert.DeserializeObject<DataTable>(result.list) 
    
        } catch(WebException)
        {
            //API 서버 닫혀있을때, 연결이 안될때
            Console.Write("예외");
            return null;
        }
        catch (Exception)
        {
            //그 외의 Exception
            Console.Write("예외");
            return null;
        }
        return dt;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-08-05
      • 2010-09-09
      • 2013-04-12
      • 2021-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多