C# : asp.net 3.5 : Deserialize JSON - json string or object? - c#

i have posted how to deserialize a json in c# but this is my question:
i got this json string :
data = #"[{""ShiftID"":""2"",""EmpName"":""dsdsfs""},{""ShiftID"":""4"",""EmpName"":""dsdsfd""}]";
and my code can deserialize it perfectly but well, if i receive this type :
data = #"[{
"Q6Option": null,
"Q5Comments": "",
"EndDate": "01/17/2012 12:57",
"Q4Comments": "",
"Active": 1,
"Q3Comments": "",
"Q8Option": null,
"Q2Comments": "",
"StartDate": "01/17/2012 12:57",
"Q3Option": null,
"Q5Option": null,
"Q1Comments": "",
"Q2Option": null,
"Station": "B1",
"Q7Option": null,
"SyncDate": null,
"ID": 1,
"Q8Comments": "",
"Q4Option": null,
"ShiftID": 1,
"EmpName": "CSM FName",
"Q1Option": null,
"Q7Comments": "",
"SyncStatus": 0,
"Q6Comments": "",
"EmpID": "111",
"createdAt": "2012-01-17T20:58:17.956Z",
"updatedAt": "2012-01-17T20:58:17.956Z",
"objectId": "XERFM5KrGv"
}]"
it doesnt work because of there is missing ""..
Well if you have an idea , thanks!

You can use the JavaScriptSerializer class that are supported from .NET framework 3.5
Reference link:
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx
Sample link:
http://msdn.microsoft.com/en-us/library/bb412170.aspx
There are some sample json texts that are same as your issue:
{"__type":"Shape:#MyApp.Shapes","x":50,"y":70}

Related

Best way to Deserialize JSON to Dynamic using C#

I'd like to know which is the best way do Deserialize to Dynamic, using NewtonSoft.Json and C#
The code below works, but I didn't like it. I would like to simplify it, using "named properties".
The main purpose is to get the last object named "results". It is an array of objects.
I know I can use a response object, but I need to use a dynamic or generic object.
var searchprod = wscli.BuscarImagensPorProdutoId(prodSku.ToString());
dynamic obj = JsonConvert.DeserializeObject<dynamic>(searchprod.Result.ToString());
dynamic obj1 = obj.results.ToString();
dynamic obj2 = JsonConvert.DeserializeObject<dynamic>(obj1);
dynamic results = ((JContainer)obj2).ToList();
if (results != null)
{
foreach (IEnumerable<JToken> item in results)
{
var prodId = item.ToList()[0];//id is first position
var id = ((JProperty)prodId).Value.ToString();
if (!string.IsNullOrEmpty(id))
{
//Delete image
var res = await wscli.ExcluirImagemProduto(id);
if (res == null || res is string)
{
throw new Exception($"Error image {id}. Details: {(res == null ? "null" : res.ToString())}");
}
if (res.status == null || res.status.ToString() != "OK")
{
throw new Exception($"Error image {id} and product {prodSku}. Details: {JsonConvert.SerializeObject(res)}");
}
}
}
}
Json:
{
"count": 5,
"next": null,
"previous": null,
"results": [
{
"id": 62217,
"image": "https://io.com/image1.jpg",
"position": 5,
"title": null,
"video": null,
"add_date": "2022-07-06T22:13:14.538307",
"change_date": "2022-07-06T22:13:14.538331",
"product": 12528,
"skus": []
},
{
"id": 62216,
"image": "https://io.com/image2.jpg",
"position": 4,
"title": null,
"video": null,
"add_date": "2022-07-06T22:13:00.435415",
"change_date": "2022-07-06T22:13:00.435436",
"product": 12528,
"skus": []
},
{
"id": 62215,
"image": "https://io.com/image3.jpg",
"position": 3,
"title": null,
"video": null,
"add_date": "2022-07-06T22:12:51.071782",
"change_date": "2022-07-06T22:12:51.071808",
"product": 12528,
"skus": []
},
{
"id": 62214,
"image": "https://io.com/image4.jpg",
"position": 2,
"title": null,
"video": null,
"add_date": "2022-07-06T22:12:35.943846",
"change_date": "2022-07-06T22:12:35.943871",
"product": 12528,
"skus": []
},
{
"id": 62213,
"image": "https://io.com/image5.jpg",
"position": 1,
"title": null,
"video": null,
"add_date": "2022-07-06T22:12:17.221066",
"change_date": "2022-07-06T22:12:17.221089",
"product": 12528,
"skus": []
}]
}
Thanks
It's not super clear what you don't like about what you have, but if you're looking to be able to access things by path / property name, something like this might work out for you. (getting strings into C# annoys me, I popped it to a file)
[TestMethod]
public void GetNode()
{
string jsonString = File.ReadAllText("json1.json");
Assert.IsNotNull(jsonString);
JObject jObject = JObject.Parse(jsonString);
// selects the node with results
var resultsNode = jObject.SelectToken("$..results");
foreach (JToken item in resultsNode)
{
Console.WriteLine(item["image"]);
}
}
I think reading this article can be useful.
https://inspiration.nlogic.ca/en/a-comparison-of-newtonsoft.json-and-system.text.json
If you have used Newtonsoft.Json features in your existing projects that are missing in System.Text.Json or have heavily decorated your DTO’s with several attributes from Newtonsoft.Json, you will probably encounter many obstacles during migration.
If you are starting a new project, I would recommend using System.Text.Json. Microsoft is constantly improving System.Text.Json and there have been significant improvements between .Net Core 3.1 and .Net 5.0 and Microsoft has already started planning for .Net 6.0.

cannot deserialize the current json object Message shows when I try to read the below Json data into Objects

Having trouble when trying to deserialize the following JSON content into objects, especially the content in eInv part
{
"requestType": "SaveDocuments",
"status": "P",
"version": "v0.1",
"validationReport": null,
"dataReport": [
{
"locationGstin": "DSAJJ0AAGCR31",
"locationName": "ABC MARKET",
"documentNumber": "2947",
"documentDate": "23-10-2020",
"billFromGstin": "DDLDF07AAGCL",
"supplyType": "S",
"documentType": "LST",
"portCode": null,
"custom1": null,
"custom2": null,
"custom3": null,
"custom4": null,
"custom5": null,
"custom6": null,
"custom7": null,
"custom8": null,
"custom9": null,
"custom10": null,
"eInv": {
"ackNumber": "1721101",
"ackDate": "01-02-2021 18:54:00",
"irn": "2d9a39998157b984276e6f1d3b8f74597d7850f0b7ba88c251556e4436b2bb0e",
"signedInvoice": "CJWeJKYynrWOw2k-GLO-vDipfOohtqW1xh5bg",
"signedQRCode": "eyJhbGciOiJSUzI1NiIsImtpZCI6IjQe5VoYONjADbEYzGABzAz8cCyLXDfNENkZ_TXHw",
"qrCode": "iVBORw0KGgoAAAANSUhEUgAAAG0AAABtCAYAAACrXCIc",
"qrCodeData": "{\"SellerGstin\":\"abc\",\"BuyerGstin\":\"def\",\"DocNo\":\"234\",\"DocTyp\":\"ghi\",\"DocDt\":\"23/10/2020\",\"TotInvVal\":4005.00,\"ItemCnt\":4,\"MainHsnCode\":\"abc\",\"Irn\":\"321absd432\",\"IrnDt\":\"2021-02-01 18:54:00\"}",
"errors": null
},
"propertyErrors": null
}
],
"referenceId": "abcdesf="
}
Find yourself a JSON aware editor, such as Visual Studio Code, or Google for any online JSON viewer and get into the habit of using these tools to check your JSON.
for example, https://jsoneditoronline.org/#left=local.taxoru&right=local.hucize gives this error with your JSON:
Parse error on line 3:
...", "qrCodeData": "{"SellerGstin":"abc","
-----------------------^
remove the first "
after "qrCodeData": and you should be valid.

JObject Parse not able to parse String with JSON type

In this method, a JSON String will be returned from GetDataSetColumns() which called API from a Signage System(Xibo) to get dataset. And I want to parse it to JSON Object.
I googled it many times and found some people have same problem too. But it seems their solution are not working for me. Such as parsing to JArray or String.Trim()
public async Task<String> GetColumnIdByName(int dataSetId, String heading)
{
String columns = await GetDataSetColumns(dataSetId);
columns.Replace("[", "");
columns.Replace("]", "");
columns.TrimStart().TrimEnd();
**JObject json = JObject.Parse(columns);**
Debug.WriteLine(json);
foreach (KeyValuePair<string, JToken> pair in json)
{
if (pair.Key.ToString().Equals("dataSetColumnId"))
{
if(pair.Value.ToString().Equals(heading))
{
return pair.Value.ToString();
}
}
}
return null;
}
Here's the JSON returned from GETDataSetColumns method and shown in Debug.
And I cannot see there is any mistakes in this JSON String.
[
{
"dataSetColumnId": 8,
"dataSetId": 3,
"heading": "item_name",
"dataTypeId": 1,
"dataSetColumnTypeId": 1,
"listContent": null,
"columnOrder": "1",
"formula": null,
"dataType": "String",
"dataSetColumnType": "Value"
},
{
"dataSetColumnId": 9,
"dataSetId": 3,
"heading": "price",
"dataTypeId": 1,
"dataSetColumnTypeId": 1,
"listContent": null,
"columnOrder": "2",
"formula": null,
"dataType": "String",
"dataSetColumnType": "Value"
},
{
"dataSetColumnId": 12,
"dataSetId": 3,
"heading": "category",
"dataTypeId": 1,
"dataSetColumnTypeId": 1,
"listContent": null,
"columnOrder": "3",
"formula": null,
"dataType": "String",
"dataSetColumnType": "Value"
},
{
"dataSetColumnId": 15,
"dataSetId": 3,
"heading": "status",
"dataTypeId": 1,
"dataSetColumnTypeId": 1,
"listContent": null,
"columnOrder": "7",
"formula": null,
"dataType": "String",
"dataSetColumnType": "Value"
}
]
And I also inspected the value of variable by Debugging mode, is it normal to have '\n' and many blankspaces? Moreover, the String.Replace and String.TrimStart() aren't working.
Debugging Mode
The exception error happens after JObject.Parse.
Exception thrown: 'Newtonsoft.Json.JsonReaderException' in Newtonsoft.Json.dll
Exception thrown: 'Newtonsoft.Json.JsonReaderException' in mscorlib.dll
An exception of type 'Newtonsoft.Json.JsonReaderException' occurred in mscorlib.dll but was not handled in user code
Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
Is there any problem of my JSON string or the way of parsing?
Thanks for any help!
I found the answer from this post
I also found other answers online but all of them are not working.
Some of them proposed define a class and deserialize the object as that defined class. But I think it isn't the right way because the structure of JSON could be dynamic.
I transfer it to JArray and retrieve the objects from it as JObject.
And it works.
I saw these comments and I think the validity of JSON isn't the main point of my problem at all.
String columns = await GetDataSetColumns(dataSetId);
JArray jArr = (JArray)JsonConvert.DeserializeObject(columns);
foreach (JObject item in jArr)
{
if(heading.Equals(item["heading"].ToString()))
{
return item["dataSetId"].ToString();
}
}
Here's example of the JSON string and I get the value by key
{
"dataSetColumnId": 12,
"dataSetId": 3,
"heading": "category",
"dataTypeId": 1,
"dataSetColumnTypeId": 1,
"listContent": null,
"columnOrder": "3",
"formula": null,
"dataType": "String",
"dataSetColumnType": "Value"
}

I am trying to deserialize JSON data to a dataset

I thought JSON was supposed to be easy to use.
I have a C# .NET Windows form program in Visual Studio 2015 being used as a client consuming a Web API 2 remote server with RestSharp as the HTTP client.
the data returned from the API call is in Json format. However, when I try to deserialize the returned Json into a dataset using this statement:
DataSet data = (DataSet)JsonConvert.DeserializeObject(response.Content, (typeof(DataSet))); ,
I get this error:
"Unexpected JSON token while reading DataTable: EndArray".
If I use the text from "response.Content" and validate it here: http://www.jsonlint.com/#, the results says "Valid JSON".
When I use the debugger to view the "response.Content" as Json, it shows the correct records that I am looking for.
I have tried different formats of JsonConvert, such as:
DataSet data = JsonConvert.DeserializeObject<DataSet>(response.Content);
DataTable datat = (DataTable)JsonConvert.DeserializeObject(response.Content, (typeof(DataTable)));
I also tried this:
XmlDocument xd1 = new XmlDocument();
xd1 = (XmlDocument)JsonConvert.DeserializeXmlNode(response.Content, "RootObject");
DataSet dataset = new DataSet();
dataset.ReadXml(new XmlNodeReader(xd1));
which I got from here: http://www.c-sharpcorner.com/blogs/how-to-parse-json-string-to-dataset-in-c-sharp1
That seems to work without giving an error, but the dataset contains four tables ( RootObject, data, CustomerRoles and ShoppingCartitems).
I tried removing three of the tables, but there are constraints and foreignkeys that I don't know how to remove and it won't allow me to remove the tables until I remove the constraints. If I try to remove the constraints, it gives this error: "Cannot remove unique constraint 'Constraint1'. Remove foreign key constraint 'RootObject_data' first."
Does anybody know how to use the "easy to use", "most popular" JSON format to deserialize my Json data into a dataset and come out with one table of data?
JSON data
{
"success": true,
"data": [{
"Id": 6,
"CustomerGuid": "70b390d8-82d5-4bba-aa68-fc8268a1b1ff",
"UserName": "victoria_victoria#nopCommerce.com",
"Email": "victoria_victoria#nopCommerce.com",
"CustomerRoles": [{
"Id": 3,
"Name": "Registered",
"SystemName": "Registered"
}],
"AdminComment": null,
"IsTaxExempt": false,
"AffiliateId": 0,
"VendorId": 0,
"HasShoppingCartItems": false,
"Active": false,
"Deleted": false,
"IsSystemAccount": false,
"SystemName": null,
"LastIpAddress": null,
"CreatedOnUtc": "\/Date(1472933472393)\/",
"LastLoginDateUtc": null,
"LastActivityDateUtc": "\/Date(1472933472393)\/",
"ExternalAuthenticationRecords": [],
"ShoppingCartItems": []
}, {
"Id": 5,
"CustomerGuid": "eb9e6f24-f362-4c10-942a-366e2919dc11",
"UserName": "brenda_lindgren#nopCommerce.com",
"Email": "brenda_lindgren#nopCommerce.com",
"CustomerRoles": [{
"Id": 3,
"Name": "Registered",
"SystemName": "Registered"
}],
"AdminComment": null,
"IsTaxExempt": false,
"AffiliateId": 0,
"VendorId": 0,
"HasShoppingCartItems": false,
"Active": false,
"Deleted": false,
"IsSystemAccount": false,
"SystemName": null,
"LastIpAddress": null,
"CreatedOnUtc": "\/Date(1472933472363)\/",
"LastLoginDateUtc": null,
"LastActivityDateUtc": "\/Date(1472933472363)\/",
"ExternalAuthenticationRecords": [],
"ShoppingCartItems": []
}, {
"Id": 4,
"CustomerGuid": "9f46dbae-6942-410c-90b8-9b38a0890064",
"UserName": "james_pan#nopCommerce.com",
"Email": "james_pan#nopCommerce.com",
"CustomerRoles": [{
"Id": 3,
"Name": "Registered",
"SystemName": "Registered"
}],
"AdminComment": null,
"IsTaxExempt": false,
"AffiliateId": 0,
"VendorId": 0,
"HasShoppingCartItems": false,
"Active": false,
"Deleted": false,
"IsSystemAccount": false,
"SystemName": null,
"LastIpAddress": null,
"CreatedOnUtc": "\/Date(1472933472317)\/",
"LastLoginDateUtc": null,
"LastActivityDateUtc": "\/Date(1472933472317)\/",
"ExternalAuthenticationRecords": [],
"ShoppingCartItems": []
}, {
"Id": 3,
"CustomerGuid": "6277386b-13ee-427b-9cfe-4ebfa487c340",
"UserName": "arthur_holmes#nopCommerce.com",
"Email": "arthur_holmes#nopCommerce.com",
"CustomerRoles": [{
"Id": 3,
"Name": "Registered",
"SystemName": "Registered"
}],
"AdminComment": null,
"IsTaxExempt": false,
"AffiliateId": 0,
"VendorId": 0,
"HasShoppingCartItems": false,
"Active": false,
"Deleted": false,
"IsSystemAccount": false,
"SystemName": null,
"LastIpAddress": null,
"CreatedOnUtc": "\/Date(1472933472253)\/",
"LastLoginDateUtc": null,
"LastActivityDateUtc": "\/Date(1472933472253)\/",
"ExternalAuthenticationRecords": [],
"ShoppingCartItems": []
}, {
"Id": 2,
"CustomerGuid": "241f45f1-b38c-4e22-8c5a-743fa3276620",
"UserName": "steve_gates#nopCommerce.com",
"Email": "steve_gates#nopCommerce.com",
"CustomerRoles": [{
"Id": 3,
"Name": "Registered",
"SystemName": "Registered"
}],
"AdminComment": null,
"IsTaxExempt": false,
"AffiliateId": 0,
"VendorId": 0,
"HasShoppingCartItems": false,
"Active": false,
"Deleted": false,
"IsSystemAccount": false,
"SystemName": null,
"LastIpAddress": null,
"CreatedOnUtc": "\/Date(1472933472207)\/",
"LastLoginDateUtc": null,
"LastActivityDateUtc": "\/Date(1472933472207)\/",
"ExternalAuthenticationRecords": [],
"ShoppingCartItems": []
}, {
"Id": 1,
"CustomerGuid": "a940dc03-5f52-47d2-9391-8597b3b31cf2",
"UserName": "tony#lakesideos.com",
"Email": "tony#lakesideos.com",
"CustomerRoles": [{
"Id": 1,
"Name": "Administrators",
"SystemName": "Administrators"
}, {
"Id": 2,
"Name": "Forum Moderators",
"SystemName": "ForumModerators"
}, {
"Id": 3,
"Name": "Registered",
"SystemName": "Registered"
}],
"AdminComment": null,
"IsTaxExempt": false,
"AffiliateId": 0,
"VendorId": 0,
"HasShoppingCartItems": true,
"Active": true,
"Deleted": false,
"IsSystemAccount": false,
"SystemName": null,
"LastIpAddress": "71.185.255.7",
"CreatedOnUtc": "\/Date(1472933470783)\/",
"LastLoginDateUtc": "\/Date(1477522483903)\/",
"LastActivityDateUtc": "\/Date(1477523996553)\/",
"ExternalAuthenticationRecords": [],
"ShoppingCartItems": [{
"Id": 1,
"StoreId": 1,
"ShoppingCartTypeId": 1,
"CustomerId": 1,
"ProductId": 18,
"AttributesXml": null,
"CustomerEnteredPrice": 0.0000,
"Quantity": 1,
"CreatedOnUtc": "\/Date(1473801903447)\/",
"UpdatedOnUtc": "\/Date(1473803336207)\/",
"IsFreeShipping": false,
"IsShipEnabled": true,
"AdditionalShippingCharge": 0.0000,
"IsTaxExempt": false
}]
}]
}
Here's a brief overview of what you need to do.
Taking from NewtonSoft - Deserialize Object example
Snippet of your data
{
"Id": 1,
"CustomerGuid": "a940dc03-5f52-47d2-9391-8597b3b31cf2",
"UserName": "tony#lakesideos.com",
"Email": "tony#lakesideos.com"
This is a Customer object. It needs it's own C# model class.
public class Customer {
int id;
string guid;
string username;
string email;
// etc...
// getters and setters...
}
This is stored in a list of data
"data": [ { ... }, { ... } ]
You need another Object to hold a list of those objects plus a boolean success value. Let's call this one Response.
{
"success": true,
"data": [{
That class starts with
public class Response {
bool success;
IList<Customer> data;
Then, you need other lists and object classes for something like this
"CustomerRoles": [{
"Id": 3,
"Name": "Registered",
"SystemName": "Registered"
}],
Once you've modeled the entire domain of classes, you should be able to have
Response res = JsonConvert.DeserializeObject<Response>(json);
Since you seem to have already tried that, and are getting an error about the END_ARRAY character, something within your DataSet class is not correctly mapped to a List
And then get res.data to access the list of data, then you can loop over those Customer objects to build your Dataset / table objects, I assume to display your data in some list of the GUI
Try starting from Response.Data instead of Response.Content, that will get you one layer in to expose the actual data to deserialize.
For example:
var response = _requestProcessor.Process<Request, Response>(
new Request(id)).dataList;
return new JsonNetResult() { Data = response, JsonRequestBehavior= JsonRequestBehavior.AllowGet };
Whatever the Request object is, it has an object that holds the responses' data in it; that is the actual item to deserialize.
Perhaps what you need to do is what Cricket_007 suggests, and make a class to encapsulate the Success object returned in the JSON, then deserialize to one Success object and a Data object, which is a list of the objects you're trying to get to.
The steps you need to follow are:
Convert the whole JSON string to an object that consists of the two objects within, Success and Data.
JSONObject content = new JSONObject(Response.Content); perhaps, this is untested.
From that object, deserialize just the Data object within it.
content.data -or- content["data"]
or some such should get you to the parts you want to work with.

Deserialize a JSON array that contains an array?

When I try to deserialize the following with the .NET JavaScriptDeserializer, I get the error message: Type 'People' is not supported for deserialization of an array
When I use JSON.NET like JsonConvert.DeserializeObject<List<People>>(args["xldata"]);, I get a more detailed error message:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'People' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
Path '[0]', line 1, position 2.
I am using Linq-To-Entities, so I don't think I can add any attributes to it.
args["xldata"] is a Dictionary with "xldata" as the key and the JSON string below as the value.
[
[
{
"CarrierHeaderId": 17,
"DetailHeaderId": 54,
"tds_client": "0000000996",
"carr_no": "0000019",
"name": "John Doe ",
"entry_type": "F",
"carrier_type": "2",
"scac_code": "1A ",
"cert_no": "2d ",
"address": "123 orange boulevard ",
"city": "Orlando ",
"state": "St",
"zip": "33333 ",
"phone": "9993023938",
"epa_num": "123 ",
"fein": "AA ",
"host_carr_no": "BB ",
"host_route_cd": "1a3 ",
"country": "US",
"CarrierHeaderLastUpdate": "6/11/2013 11:07 AM",
"term_id": "TDSTES8",
"trailer_req": "0",
"truck_req": "0",
"access_from": "1159",
"access_to": "2359",
"access_days": "YNNYYYN",
"ins_exp_date": "12/20/13",
"locked": "",
"lockout_date": "",
"lockout_reason": "",
"st_license": "",
"st_permit": "",
"icc_permit": "",
"liab_amt": "",
"haz_mat_excl": "",
"veh_liab_exp": "",
"veh_liab_amt": "",
"excess_liab_exp": "",
"excess_liab_amt": "",
"work_comp_exp": "",
"work_comp_amt": "",
"host_locked": "",
"host_lockout_date": "",
"host_lockout_reason": "",
"po_relno_req": null,
"general_exp": "",
"general_amt": "",
"access_profile": "",
"max_load_amt": "",
"own_consumption": "",
"full_redirect": "",
"det_required": "",
"seal_processing": "",
"email_group": "",
"email_address": "",
"shipment_origin": "",
"auto_confirm": "",
"bulk_transaction_picklist": "",
"ExciseNo": "",
"ERP_Carrier": "",
"CarrierDetailLastUpdate": "6/11/2013 5:03 PM"
}
]
]
JsonConvert.DeserializeObject<List<List<People>>> should work.

Categories

Resources