Click here to Skip to main content
15,890,506 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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": []
}

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;
Posted
Updated 15-Mar-17 14:16pm
Comments
j snooze 15-Mar-17 17:17pm    
Are you trying to only get the vehicle make out of this, or do you need each separate object(vehicle year, model, product etc...)?
Samira Radwan 16-Mar-17 8:33am    
I nedd all the object, using vehicle make as an example

1 solution

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
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.
C#
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;
        }
    }
}
 
Share this answer
 
v2
Comments
Samira Radwan 16-Mar-17 9:55am    
Thank you for the answer, I have followed your code and created all the classes and in [Main] this is my full code:

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(); }
var data = JsonHelper.ToClass<response>(JSONfile);
Debugger.Break();

no errors but (data) is null, i mean all the objects are null (makes/models ....), Am I missing something? Thank you!
Graeme_Grant 16-Mar-17 9:58am    
The above code was checked and worked fine.

Have you set a breakpoint and checked if JSONfile has any data?
Samira Radwan 16-Mar-17 9:58am    
Also If I want to create DT from each object separately, how to manage this? Thanks again!!
Graeme_Grant 16-Mar-17 10:03am    
That is a difficult open-ended question to answer. The structure is not flat.

You would have to define what and how. That is outside of the scope of this Q&A and will require a new question once you have scoped it out and given it a go. The issue here was decoding the Json data and that was covered in the above solution.
Samira Radwan 16-Mar-17 10:15am    
Actually , you're right.
I will try to extract all the data I need from the objects been created
Thanks again, saved me a lot of time!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900