Jsonconvert deserializeobject error

Hi

Hi

I’m using this code to deserialize my json data to list of objects as follow :

public static List<T> DeserializeListFromTempData<T>(HttpContext context, string strName)
        {
            List<T> lstResult = null;

            var iTempData = HelperMethods.GetTempData(context);
            var tmp = iTempData.Peek(strName);
            if (tmp != null)
            {
                lstResult = JsonConvert.DeserializeObject<List<T>>(tmp.ToString(), new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
            }

            return lstResult;
        }

And usage :

List<DefaultVisitProductDetails> lstPackageDetails = HelperMethods.DeserializeListFromTempData<DefaultVisitProductDetails>(this.HttpContext, "_lstPackageDetails");

The above codes works correctly. However, when i use it inside another generic method as follow :

public static void AttachDetailsListToDbContext<T, TDetails, TField>(HttpContext context, string strName, DbContext dbContext, object masterObjectGraph, Expression<Func<T, TDetails>> details, Expression<Func<T, TField>> field, TField value, InternalHelperAction action) where T : class
        {
List<TDetails> lstPackageDetails = HelperMethods.DeserializeListFromTempData<TDetails>(context, strName);
...
}

i’m facing the following problem :

Cannot deserialize the current JSON object (e.g. {«name»:»value»}) into type ‘System.Collections.Generic.ICollection`1[EFCoreTest.Models.DefaultVisitProductDetails]’ because the type requires
a JSON array (e.g. [1,2,3]) to deserialize correctly.

To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array
or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.

Where is the problem & how to solve it?

Thanks in advance


http://www.codeproject.com/KB/codegen/DatabaseHelper.aspx

Json.NET supports error handling during serialization and deserialization. Error handling lets
you catch an error and choose whether to handle it and continue with serialization or let the error
bubble up and be thrown in your application.

Error handling is defined through two methods:
the Error event on JsonSerializer and the OnErrorAttribute.

Error Event

The Error event is an event handler found on JsonSerializer. The error event is raised whenever an
exception is thrown while serializing or deserialing JSON. Like all settings found on JsonSerializer
it can also be set on JsonSerializerSettings and passed to the serialization methods on JsonConvert.

List<string> errors = new List<string>();
 
List<DateTime> c = JsonConvert.DeserializeObject<List<DateTime>>(@"[
  ""2009-09-09T00:00:00Z"",
  ""I am not a date and will error!"",
  [
    1
  ],
  ""1977-02-20T00:00:00Z"",
  null,
  ""2000-12-01T00:00:00Z""
]",
  new JsonSerializerSettings
    {
      Error = delegate(object sender, ErrorEventArgs args)
        {
          errors.Add(args.ErrorContext.Error.Message);
          args.ErrorContext.Handled = true;
        },
      Converters = { new IsoDateTimeConverter() }
    });
 
// 2009-09-09T00:00:00Z
// 1977-02-20T00:00:00Z
// 2000-12-01T00:00:00Z
 
// The string was not recognized as a valid DateTime. There is a unknown word starting at index 0.
// Unexpected token parsing date. Expected String, got StartArray.
// Cannot convert null value to System.DateTime.

In this example we are deserializing a JSON array to a collection of DateTimes. On the JsonSerializerSettings
a handler has been assigned to the Error event which will log the error message and mark the error as handled.

The result of deserializing the JSON is three successfully deserialized dates and three error messages:
one for the badly formatted string, «I am not a date and will error!», one for the nested JSON array and one
for the null value since the list doesn’t allow nullable DateTimes. The event handler has logged these messages
and Json.NET has continued on deserializing the JSON because the errors were marked as handled.

One thing to note with error handling in Json.NET is that an unhandled error will bubble up and raise the event
on each of its parents, e.g. an unhandled error when serializing a collection of objects will be raised twice,
once against the object and then again on the collection. This will let you handle an error either where it
occurred or on one of its parents.

JsonSerializer serializer = new JsonSerializer();
serializer.Error += delegate(object sender, ErrorEventArgs args)
  {
    // only log an error once
    if (args.CurrentObject == args.ErrorContext.OriginalObject)
      errors.Add(args.ErrorContext.Error.Message);
  };

If you aren’t immediately handling an error and only want to perform an action against it once then
you can check to see whether the ErrorEventArg’s CurrentObject is equal to the OriginalObject.
OriginalObject is the object that threw the error and CurrentObject is the object that the event is being raised
against. They will only equal the first time the event is raised against the OriginalObject.

OnErrorAttribute

The OnErrorAttribute works much like the other .NET serialization attributes that Json.NET supports.
To use it you simply place the attribute on a method which takes the correct parameters: a StreamingContext and a ErrorContext.
The name of the method doesn’t matter.

public class PersonError
{
  private List<string> _roles;
 
  public string Name { get; set; }
  public int Age { get; set; }
  public List<string> Roles
  {
    get
    {
      if (_roles == null)
        throw new Exception("Roles not loaded!");
 
      return _roles;
    }
    set { _roles = value; }
  }
  public string Title { get; set; }
 
  [OnError]
  internal void OnError(StreamingContext context, ErrorContext errorContext)
  {
    errorContext.Handled = true;
  }
}

In this example accessing the the Roles property will throw an exception when no roles have
been set. The HandleError method will set the error when serializing Roles as handled and allow Json.NET to continue
serializing the class.

PersonError person = new PersonError
  {
    Name = "George Michael Bluth",
    Age = 16,
    Roles = null,
    Title = "Mister Manager"
  };
 
string json = JsonConvert.SerializeObject(person, Formatting.Indented);
 
Console.WriteLine(json);
//{
//  "Name": "George Michael Bluth",
//  "Age": 16,
//  "Title": "Mister Manager"
//}

System.Text.Json.JsonException: Serialization JSON error for the invalid start of a property name

Issue Description

.NET code serialization using gives an error for a single quote and forces you to use a double quote.

System.Text.Json.JsonException: ”” is an invalid start of a property name. Expected a ‘”‘. Path: $ | LineNumber: 0 | BytePositionInLine: 1.’

or

System.Text.Json.JsonException: “’s’ is an invalid start of a value is an invalid start of a property name. Expected a ‘”‘. Path: $ | LineNumber: 0 | BytePositionInLine: 1.’

SystemText Json JsonException is an invalid start of a property name Expected a

Resolution

I had this issue recently for one of the existing codes which was working perfectly fine with NewtonSoft JSON as a serializer.

I was trying to replace Newtonsoft with System.Text.Json.

The issue I found to be due to strict JSON specification usage by Microsoft as per RFC 8259.

Few issues I was able to fix easily by using some options but some issues which I thought Initially, could be fixable but found the limitation on System.Text.Json’s usage.

Reference: RFC 8259 

As per Microsoft,

A value enclosed in single quotes will result in a JsonException. System.Text.Json shall accept property names and string values only in double-quotes as per RFC 8259 specification.

Below JSON sample are considered Invalid format,

Invalid Format of JSON

Invalid Format which throws JsonException,

OR

Note- Above both formats however works perfectly fine for Newtonsoft.Json serialization. but you may want to consider that as short term solution ?

Valid Format of JSON

Example

object to JSON string serialize and deserialize 1'''' is an invalid start of a property name

OR

String must not use double quotes JsonException is an invalid start of a property name

So here although this is not the resolution but rather additional information on the current design and limitation on System.Text.Json usage.

So please plan accordingly… and good luck.

Other scenarios causing “invalid start of a property name”

Comments in JSON fields are not allowed as default behavior while using System.Text.Json.

If you have comments or trailing commas in the JSON, the above error will be produced.

Example:

{
  "Bank": "Bank of ABCD", //This is Bank Id
  "BranchInfo": [
    {
        "Location": 
          {
            "Street": "address1", //
            "Zip": "Zip",       /*This is zip code*/
            "State": "USA"
          }  
    }
  ]
}

To fix the issue either remove comments or add JSON option with a serializer or deserializer to allow the comments.

Please see the below article for more details,

  • System.Text.Json – Allow Comments or trailing commas in JSON

Other Useful Reference:

  • Serialize and Deserialize using System.Text.Json
  • Create Custom Converters for JSON serialization in .NET with example

Did I miss anything else in these resolution steps?

Did the above steps resolve your issue? Please sound off your comments below!

Happy Coding !!


Please bookmark this page and share it with your friends. Please Subscribe to the blog to get a notification on freshly published best practices and guidelines for software design and development.


Please Subscribe to the blog to get a notification on freshly published blogs and best practices of software development.

When working on API automation, I had to deserialize response for parsing the API response data. We used Newtonsoft.Json NuGet for the same.

I faced below error during deserialization –

Newtonsoft.Json.JsonSerializationException

  HResult=0x80131500

  Message=Error converting value "{"Id":"92209","operatorId":100000,"acctId":1000,"status":true}" to type 'Model'. Path '', line 1, position 726.

  Source=Newtonsoft.Json

  StackTrace:

   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)

   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)

   at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)

   at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings)

   at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings)

   at CommonLibraries.CommonLibrary.GetResponseBodyDictionary(RestResponse response, Int32 statusCode) in C:CommonLibrariesCommonLibrary.cs:line 35

   at Test(String id, String TestDescription, Int32 statusCode, String TemplateId) in C:Tests.cs:line 108

 Inner Exception 1:

ArgumentException: Could not cast or convert from System.String to Model. 

Initially thought –

  • Json response is not in the correct format
  • not all properties are included in the Json.

But that was not the reason.

After multiple googlings, tried to –

  • trim the Json content
  • replace escape characters
  • Html decode the Json.

None of these worked.

Finally, this StackOverflow post helped to resolve the issue. Looks like the content i’m deserializing is serialized multiple times, I had to deserialize as a string and then deserilize again to the model to resolve the issue. Below code worked for me.

   var content = response.Content;              
   var jsonResult = JsonConvert.DeserializeObject(content).ToString();
   var result= JsonConvert.DeserializeObject<Model>(jsonResult);

Here content is similar to “”{\”Id\”:\”92209\”,\”operatorId\”:100000,\”Status\”:true}”

  • deserialization
  • Json
  • Newtonsoft
  • NuGet
  • Troubleshooting
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
[
    {
        "id": 7542826,
        "title": "Адрес 140",
        "address": "Адрес 140",
        "longitude": 05.961548,
        "latitude": 04.742206,
        "kkms": [
            {
                "id": 65231138,
                "orgId": 3122,
                "retailPlaceId": 7128126123,
                "internalName": "000423532061244",
                "model": "ZR2",
                "serialNumber": "0364589429",
                "onlineStatus": 1,
                "status": 4,
                "createdAt": 1580367599792,
                "declineReason": "",
                "fnsKkmId": "15975313354061244",
                "regStatus": "REGISTRATION_SUCCESS",
                "regStatusChangedAt": 165465370307890,
                "fiscalDrive": {
                    "producer": "",
                    "number": "54165453465469161",
                    "activationDate": 1580367540000
                },
                "lastShift": {
                    "kkmId": "5275257275061244",
                    "updateDate": 1752752752396335,
                    "shiftNumber": 187243,
                    "sells": 8895.61,
                    "returns": 0,
                    "lastTransaction": 1597252577410360000,
                    "shiftClosed": false,
                    "fiscalDriveReplaceRequired": false,
                    "fiscalDriveMemoryExceeded": false,
                    "fiscalDriveExhausted": false,
                    "fiscalDocumentsCount": 47,
                    "lastTransactionType": "TICKET"
                }
            },
            {
                "id": 657765130,
                "orgId": 3122,
                "retailPlaceId": 7128126123,
                "internalName": "000433185565000601",
                "model": "ZR2",
                "serialNumber": "08388284512361",
                "onlineStatus": 0,
                "status": 4,
                "createdAt": 1584534534534507,
                "declineReason": "",
                "fnsKkmId": "0004534534534530601",
                "regStatus": "REGISTRATION_SUCCESS",
                "regStatusChangedAt": 15453453453890,
                "fiscalDrive": {
                    "producer": "",
                    "number": "45354345354345566357",
                    "activationDate": 4534534534560000
                },
                "lastShift": {
                    "kkmId": "45354345345300601",
                    "updateDate": 1596094816137,
                    "shiftNumber": 1611,
                    "sells": 0,
                    "returns": 0,
                    "lastTransaction": 1597252577410360000,
                    "shiftClosed": false,
                    "fiscalDriveReplaceRequired": false,
                    "fiscalDriveMemoryExceeded": false,
                    "fiscalDriveExhausted": false,
                    "fiscalDocumentsCount": 0,
                    "lastTransactionType": "OPEN_SHIFT"
                }
            }
        ],
        "kkmsOnlineCount": 2
    }
]

Понравилась статья? Поделить с друзьями:
  • Json validation error list
  • Json rpc коды ошибок
  • Js catch specific error
  • Js axios catch error code
  • Jrpcexception asn 1 decode error offset 0 unexpected end of buffer encountered что это