JSON文件到数据表 [英] JSON file to datatable(s)

查看:58
本文介绍了JSON文件到数据表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨专家,



我知道之前可能会多次询问并且有很多解决方案,但没有一个适用于我。我有一个JSON文件需要转换为datatable(s)。

我试图使用 JsonConvert.DeserializeObject< class>(JSONFILE)

还尝试了 JsonConvert.DeserializeAnonymousType

并尝试转换为对象/数组

以上所有方法都返回错误。请参阅下面的JSON文件和我尝试过的代码。



提前致谢!!

Samira



我的尝试:



JSON档案

Hi Experts,

I know this might been asked many times before and has many solutions out there but none works for me. I have a JSON file need to convert to datatable(s).
I have tried to use JsonConvert.DeserializeObject<class>(JSONFILE)
Also tried JsonConvert.DeserializeAnonymousType
and tried to convert to object / array
all above methods return errors. Please see below the JSON file and the code I have tried.

Thanks in advance!!
Samira

What I have tried:

JSON File

{
  "vehicle-make": {
    "id": "kia",
    "name": "Kia",
    "path": "p"
  },
  "vehicle-year": {
    "id": "2016-std-key",
    "name": "2016 Std. Key",
    "path": "p1"
  },
  "vehicle-model": {
    "id": "rio",
    "name": "Rio",
    "path": "p2"
  },
  "product": {
    "id": "orbit000a",
    "name": "ORBIT000A",
    "path": "/v1/catalog/orbit000a",
    "description": "description",
    "category": "kit"
  },
  "coverage": {
    "t-harness-support": false,
    "\"track-pack\"-gauges": false,
    "2-way-serial-data-communication": false,
    "3xlock-start-from-oem-remote": false,
    "3xlock-start-w-aftermarket-starter": false    
  },
  "accessories": []
}



将JSON转换为DT的不同方法


Different ways to convert JSON to DT

HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.Headers.Add(headerKey, headerVal);
            httpWebRequest.Method = WebRequestMethods.Http.Get;
            httpWebRequest.Accept = "application/json; charset=utf-8";
            string JSONfile;
            var response = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var sr = new StreamReader(response.GetResponseStream()))
            { JSONfile = sr.ReadToEnd(); }
            JSONfile = JSONfile.Replace("vehicle-make", "vehiclemake"); 
            JSONfile = JSONfile.Replace("vehicle-year", "vehicleyear");
            JSONfile = JSONfile.Replace("vehicle-model", "vehiclemodel");

            //****method(1)**** error unexpected end of data
            var obj = JObject.Parse(JSONfile);
            var array = new JArray(obj["vehiclemake"].Values());
            var dt = array.ToObject<DataTable>();
         //**** method(2) return null object
         clsMakes make = JsonConvert.DeserializeObject<clsMakes>(JSONfile);
        //also tried with list 
//Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[ApiConnect.clsMakes]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly
       var make = JsonConvert.DeserializeObject<List<clsMakes>>(JSONfile);
      //class clsMakes
    class clsMakes
    {
        
        public string id {get;set;}
        public string name { get; set; }
        public string path { get; set; }
    }
//method(3)
//Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path 'vehiclemake'
var makeTB = JsonConvert.DeserializeAnonymousType(JSONfile, new { vehiclemake = default(DataTable) }).vehiclemake;

推荐答案

您遇到的问题是您有复杂的节点名称,而不是直接转换为.Net变量名称。因此动态对象创建失败。



例如:
The problem that you are having is that you have complex node names that don't directly translate to .Net variable names. So Dynamic object creation is failing.

Examples of this are:
vehicle-model
\"track-pack\"-gauges
3xlock-start-from-oem-remote

所有都是无效名称.Net名称但有效的Json节点名称。



这并不意味着这是不可能的,这意味着你必须手动完成。

All are invalid names .Net names but valid Json Node names.

This does not mean that it is not possible to do, it means that you have to do it manually.

using Newtonsoft.Json;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

namespace JsonConverter2
{
    class Program
    {
        static void Main(string[] args)
        {
            string raw = File.ReadAllText("data.json");
            var data = JsonHelper.ToClass<Response>(raw);
            Debugger.Break();
        }
    }

    public class VehicleMake
    {

        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("path")]
        public string Path { get; set; }
    }

    public class VehicleYear
    {

        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("path")]
        public string Path { get; set; }
    }

    public class VehicleModel
    {

        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("path")]
        public string Path { get; set; }
    }

    public class Product
    {

        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("path")]
        public string Path { get; set; }

        [JsonProperty("description")]
        public string Description { get; set; }

        [JsonProperty("category")]
        public string Category { get; set; }
    }

    public class Coverage
    {

        [JsonProperty("t-harness-support")]
        public bool THarnessSupport { get; set; }

        [JsonProperty("\"track-pack\"-gauges")]
        public bool TrackPackGauges { get; set; }

        [JsonProperty("2-way-serial-data-communication")]
        public bool AA2WaySerialDataCommunication { get; set; }

        [JsonProperty("3xlock-start-from-oem-remote")]
        public bool AA3xlockStartFromOemRemote { get; set; }

        [JsonProperty("3xlock-start-w-aftermarket-starter")]
        public bool AA3xlockStartWAftermarketStarter { get; set; }
    }

    public class Response
    {

        [JsonProperty("vehicle-make")]
        public VehicleMake VehicleMake { get; set; }

        [JsonProperty("vehicle-year")]
        public VehicleYear VehicleYear { get; set; }

        [JsonProperty("vehicle-model")]
        public VehicleModel VehicleModel { get; set; }

        [JsonProperty("product")]
        public Product Product { get; set; }

        [JsonProperty("coverage")]
        public Coverage Coverage { get; set; }

        [JsonProperty("accessories")]
        public IList<object> Accessories { get; set; }
    }

    public static class JsonHelper
    {
        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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆