Siavosh Tehrani Siavosh Tehrani - 2 months ago 16
JSON Question

Deserialing json object to array of object

I have a Json in file added to my project embedded resource.
I want to read this file which contains a list of certain object and deserialize it.

I have following Json file:

[
{
"Status": 21,
"CustomerId": "e3633ccb-bbea-465d-9ce6-6c37e9c40e2e"
},
{
"Status": 20,
"CustomerId": "d02e2970-7c28-41b0-89f3-5276a97e12c9"
}
]


and following model:

public class CustomerStatus
{
public int Status { get; set; }
public string CustomerId { get; set; }
}


as I read the jSon file from resource, it is automatically in form of array of byte and as I convert it to string, it has \r\n and \t in it.

in my code I have following lines do achieve this but it fails:

var string customerdata = System.Text.Encoding.UTF8.GetString(myResources.CustomerStatus);
var data = JsonConvert.DeserializeObject<List<CustomerStatus>>(customerdata);


I receive this error:
threw an exception of type 'Newtonsoft.Json.JsonReaderException' Message "Unexpected character encountered while parsing value: . Path '', line 0, position 0."

UPDATE:

following line also result the same issue:

var string customerdata = System.Text.Encoding.UTF8.GetString(myResources.CustomerStatus);
.Replace("\r\n", " ")
.Replace("\t", " ");

Answer

It seems an encoding problem of the file. You can use Notepad++ to convert the file or you can open your JSON file using Notepad and use Save As selecting ANSI as encoding. Then Remove and Add the file again in your resources and switch System.Text.Encoding.UTF8.GetString(myResources.CustomerStatus)

to

System.Text.Encoding.ASCII.GetString(myResources.CustomerStatus)

If you are keen to use UTF8, then use Notepad++ to convert the file instead.

Comments