1

I extract JSON code from an API

There is no problem with that

the JSON output is this string

\"[\\r\\n  {\\r\\n    \\\"PtsID\\\": 14061\\r\\n  }\\r\\n]\"

but when I try to convert this to a datatable

using this line of code

Here is my code

    DataTable dt1 = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));

I get this error

Newtonsoft.Json.JsonSerializationException: 'Unexpected JSON token when reading DataTable. Expected StartArray, got String. Path '', line 1, position 46.'

I tried analysing the json string but no luck finding what could cause this error!!!

here is my code

      HttpClient client = new HttpClient();

        client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));

        string json = client.GetStringAsync(url).Result;

        DataTable dt1 = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));

Edit

I looked at this answer here

Deserialize a nested DataSet from Json String with Json.NET

and changed my code to this

    class MyTableUtilClass
    {
        public string PtsID { get; set; }
        public DataTable Table { get; set; }
    }

        HttpClient client = new HttpClient();

        client.DefaultRequestHeaders.Accept.Add(
        new MediaTypeWithQualityHeaderValue("application/json"));

        string json = client.GetStringAsync(url).Result;

        var myUtil = JsonConvert.DeserializeObject<MyTableUtilClass>(json);
        DataTable myTable = myUtil.Table;

but when reach this line

        var myUtil = JsonConvert.DeserializeObject<MyTableUtilClass>(json);

I get this error

Newtonsoft.Json.JsonSerializationException: 'Error converting value "[ { "PtsID": 14061 } ]" to type 'Encoder.FrmCoder+MyTableUtilClass'. Path '', line 1, position 46.'

which is the same error i got before..

any solution?

Edit

In the API I convert a datatable into JSON

so I can convert the JSON back to datatable in the application

Here is the code from the API

[Route("api/SearchSelect")]
        public string Get(string P1 = null, string P2 = null, string P3 = null, string P4 = null)
        {
            SqlConnection conn = new SqlConnection(gDBConn);
            SqlCommand cmd = new SqlCommand("SearchSelect", conn);
            cmd.CommandTimeout = 0;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@PtsName", P1));
            cmd.Parameters.Add(new SqlParameter("@PtsNo", P2));
            cmd.Parameters.Add(new SqlParameter("@RepCode", P3));
            cmd.Parameters.Add(new SqlParameter("@RepText", P4));

            try
            {
                conn.Open();

                SqlDataReader rdr = cmd.ExecuteReader();

                var dt = new DataTable();
                dt.Load(rdr);
                List<DataRow> result = dt.AsEnumerable().ToList();
                rdr.Close();
                string json = DataTableToJSON(dt);
                return json;
            }
            catch (Exception ex)
            {
                return ex.Message;
            }

        }

    public string DataTableToJSON(DataTable dt)
    {
        string JSONString = string.Empty;
        string json = JsonConvert.SerializeObject(dt, Formatting.Indented);

        return json;
    }
0

2 Answers 2

1

The problem you're seeing is that your json doesn't represent an array: it represents a string. Hence, the error message (expecting [ and getting " instead). Ideally, try to figure out how the original JSON is getting converted into a string, and work to correct the problem at its source, so you get a JSON string like this instead:

[
  {
    "PtsID": 14061
  }
]

Looking at your API, I'm guessing you're using a framework that takes whatever value is returned and tries to JSON-serialize it. So even though you already JSON-serialized the DataTable into a string, that string is getting serialized again by whatever API framework you're using (like WebApi).

Have you tried simply returning the DataTable, to see whether it gets serialized correctly without your having to do it?

return dt;

If that doesn't work, you might consider returning something like a JArray instead of a string:

return JArray.FromObject(dt1);

If you have no control over the source, you'll need to unwrap the JSON yourself, like this:

var unwrappedJson = JsonConvert.DeserializeObject<string>(json);
DataTable dt1 = (DataTable)JsonConvert.DeserializeObject(unwrappedJson, (typeof(DataTable)));
Sign up to request clarification or add additional context in comments.

Comments

0

BTW, you can get this same error message if you call a WebAPI and fail to have the proper character set. Since it seems nobody has documented this error in this way anywhere else, I figured I'd save someone the hour I spent figuring this out.

            var request = new RestRequest();
            request.AddHeader("Accept", "application/json; charset=utf-8");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.