-2

I am absolutely new in Json stuff, following is one of my returned JSON string from one of the Internal REST API Call:

{
   "odata.metadata":"https://ABC.XYZ.com/ERP10TESTNSSO/api/v1/Erp.BO.ABCCodeSvc/$metadata#Epicor.RestApi.ABCCodes/@Element",
   "Company":"93100",
   "ABCCode1":"A",
   "CountFreq":1,
   "ExcludeFromCC":false,
   "StockValPcnt":"0",
   "PcntTolerance":"0.00",
   "CalcPcnt":false,
   "CalcQty":false,
   "CalcValue":false,
   "QtyTolerance":"0",
   "ValueTolerance":"0",
   "ShipToCustNum":0,
   "SysRevID":"6066188743",
   "SysRowID":"5b7e2172-7f7a-445e-983d-f230e050153d",
   "BitFlag":0,
   "RowMod":""
}

Please let me know, how may I convert it into C# Data Table?

I tried following code (posted by another kind techie)

dynamic jsonObject = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonContent);
DataTable dt = JsonConvert.DeserializeObject<DataTable>(Convert.ToString(jsonObject.Value));

But this code is throwing error at jsonObject.Value.

Please help me to fix it ...

24x7
  • 5
  • 2
  • Using Json.Net you can [deserialize directly to a data table...](https://stackoverflow.com/questions/7641004/how-to-convert-json-into-datatable) However, your json only contain a single object, not a json array, so I'm not sure that deserializing it to a data table would be the correct choice here... – Zohar Peled Aug 19 '20 at 08:22
  • Every time you use `dynamic` some part of the world dies a sad lonely death... (with random unhelpful errors) – TheGeneral Aug 19 '20 at 08:24
  • you need to do several steps, first of all, read about Json, the main problem that you have got is that dt sees columns, among other things, and you are throwing data, without naming it, it does not make any sense. Secondly, define a class where the properties are the name of the Json properties, then create the object and deserialize, I am sure that you can work out how to transform from an object to a datatable – Iria Aug 19 '20 at 08:25

1 Answers1

0

Try this:

 string json = "{\"odata.metadata\":\"https://ABC.XYZ.com/ERP10TESTNSSO/api/v1/Erp.BO.ABCCodeSvc/$metadata#Epicor.RestApi.ABCCodes/@Element\",\"Company\":\"93100\",\"ABCCode1\":\"A\",\"CountFreq\":1,\"ExcludeFromCC\":false,\"StockValPcnt\":\"0\",\"PcntTolerance\":\"0.00\",\"CalcPcnt\":false,\"CalcQty\":false,\"CalcValue\":false,\"QtyTolerance\":\"0\",\"ValueTolerance\":\"0\",\"ShipToCustNum\":0,\"SysRevID\":\"6066188743\",\"SysRowID\":\"5b7e2172-7f7a-445e-983d-f230e050153d\",\"BitFlag\":0,\"RowMod\":\"\"}";

 json = $"[{json}]";

 DataTable dt = JsonConvert.DeserializeObject<DataTable>(json);

Add [ ] in your json string.

24x7
  • 5
  • 2
逍遥子k
  • 177
  • 5