JossVAMOS
JossVAMOS

Reputation: 310

Json.NET JsonConvert.DeserializeObject() return null value

i tried to Deserialize this string :

string _jsonObject = {\"Ad\":{\"Type\":\"Request"\,
         \"IdAd\":\"[email protected]\",
         \"Category\":\"cat\",
         \"SubCategory\":\"subcat\"},
\"Position\":{\"Latitude\":\"38.255\",
              \"Longitude\":\"1.2\",
              \"Imei\":\"0123456789\"};
}";

Message _message = JsonConvert.DeserializeObject<Message>(_jsonObject);

Works pretty for "Ad" but not instanciate "Position". Any idea ?

Upvotes: 15

Views: 88123

Answers (12)

mathe_matician
mathe_matician

Reputation: 109

In my case, I was naively trying to do extra logic in my constructor that I was deserializing into.

When trying to deserialize via var deserializedItem = JsonConvert.DeserializeObject<MyClass>(item);, the constructor of MyClass would show that all values were empty, even though the log statement before deserializing showed a valid JSON string.

So if it is helpful for you or for anyone else, that may be another area to check. In your case the Message class ctor may contain additional logic.

E.g.

public Message(string _thing1, string _thing2)
{
   // setting values here
   thing1 = _thing1;
   byte[] data = Convert.FromBase64String(thing1);
   // doing more stuff with data
   thing2 = _thing2;
}

Upvotes: 0

upsidedowncreature
upsidedowncreature

Reputation: 627

In my case it was because I had forgotten to decorate the Location property with the JsonPropertyName attribute. Fixed by changing:

public LatLongLocation Location {get; set; }

to:

[JsonPropertyName("location")]
public LatLongLocation Location {get; set; }

Upvotes: 0

AnasSafi
AnasSafi

Reputation: 6244

In my case the problem was deserializeobject return null when try to convert null value from json to int.

    public class ItemCalcResModel
    {
        public int cartId;
    }

I solved the problem by enable nullable in project:

    #nullable enable
    public class ItemCalcResModel
    {
        public int? cartId;
    }

Upvotes: 0

Ocean Airdrop
Ocean Airdrop

Reputation: 2921

In my case, it was because I did not have a public constructor on my class.

This is what my class originally looked like:

public class TreeGroup
{
    public string Name { get; set; }
    public SiteGroup Group { get; set; }
    public List<TreeMimicObject> Children { get; set; }
   
    public TreeGroup(SiteGroup item)
    {
        // Notice this constructor takes a SiteGroup object and there 
        // is no default constructor
    }
}

so I changed the class from the above to this:

public class TreeGroup
{
    public string Name { get; set; }
    public SiteGroup Group { get; set; }
    public List<TreeMimicObject> Children { get; set; }

    public TreeGroup()
    {
        // Added this default constructor here!!
    }

    public TreeGroup(SiteGroup item)
    {
        // ...
    }
}

and it worked!

Upvotes: 0

Eternal21
Eternal21

Reputation: 4664

I've never had any issues using Newtonsoft.Json, but decided to go with built in json libraries in latest project. Ended up with null result. Turns out the following will fail:

JSON:

{
   "myProperty": "abc"
}

CLASS:

public void MyClass
{
   public string MyProperty { get; set; }
}

Why does it fail? "myProperty" in json is camel case (starts with lower case letter), while MyProperty in MyClass starts with upper case letter. If you make both cases the same it works. I tried figuring out how to configure case insensitivity for the entire app, but apparently that's not possible to do, so I went back to Newtonsoft.JSON and the problem went away.

Upvotes: 1

Arash Masir
Arash Masir

Reputation: 205

In my case, my class properties had internal setters and after setting them public the problem solved.

Upvotes: 5

Sam
Sam

Reputation: 922

My problem was that I was including the class name at the beginning of my JSON string. I had copy-pasted from the serialized output of another class that contained the one I wanted to deserialize and I had purposefully included the class name thinking this was the correct JSON string. Once I removed the class name from my JSON string, it deserialized just fine.

This article was helpful in realizing this: https://social.msdn.microsoft.com/Forums/windowsapps/en-US/4d766a28-ff38-477f-8abf-48ed01f74cd2/jsonconvertdeserializeobjectlttgtjsonstring-returning-all-propertieslttgt-as-null?forum=wpdevelop

I did not see this answer here so I am including it hoping that it helps those who made the same silly mistake as me.

Upvotes: 2

Moshe
Moshe

Reputation: 21

In my case there is a more subtle error. It is easy to add leading or trailing spaces in the json keys by mistake. When that happens, the key is not recognized and attempting to deserialize it sets the value to null.

For example: {" id": 123}
This id field is not recognized because of the leading space " id". To fix it, fix the json to have instead "id".

Upvotes: 2

user2016089
user2016089

Reputation:

Make sure the name of array in JSON matches with property name in your class

Illustrating (Look for "Components"):

JSON:

{  
  "Components": [
    {
      "Attribute1": "ABC",
      "Attribute2": "XYZ"      
    }
  ]
}

Class:

public class MyClass
{
    public IList<Component> Components { get; set; }
}

Deserialize:

JsonConvert.DeserializeObject<MyClass>(File.ReadAllText(@"ComponentSet.json"))

Upvotes: 2

KthProg
KthProg

Reputation: 2117

I forgot to make the properties public. Don't forget to do that...

Upvotes: 50

Dave Parker
Dave Parker

Reputation: 664

In the interest of helping others that may be experiencing this issue, or one related to it...

In my case, I had an object with an array of other objects, and one of the reference-type properties on those sub-objects was always null after deserialization. I tried all kinds of things, including downloading the JSON.Net source and stepping through it to find the failure point.

To make a long story short, the problem was, of course, my own. Here is a highly simplified version of my JSON and classes.

JSON

{
    "$id": "1",
    "RowCount": 10,
    "Rows": [{
        "$id": 2",
        "ItemId": "1",
        "ItemName": "Some Item",
        "Owner": {
            "Name": "John Doe",
            "Id": "711D04F5-586F-4FD4-8369-4C00B51DD86F",
            // other properties...
        },
        "OwnerId": "711D04F5-586F-4FD4-8369-4C00B51DD86F"
    },
    // more rows
    ]
}

Classes

public class Items
{
    public int RowCount { get; set; }
    public IEnumerable<Item> Rows { get; set; }
}

public class Item
{
    private string ownerId;

    public string ItemId { get; set; }
    public string ItemName { get; set; }
    public Person Owner { get; set; }
    public string OwnerId
    {
        get { return this.ownerId; }
        set {
            if (value != this.ownerId)
            {
                this.Owner = null;
            }
            this.ownerId = value;
        }
    }
}

public class Person
{
    public string Name { get; set; }
    public string Id { get; set; }
    // other properties
}

What was happening is that, because the Owner property appeared in the JSON prior to the OwnerId property, when the OwnerId property was set, the setter code determined that the current value was not the same as the value being set (since the current value was null), so it set the Owner property to null.

To fix it I also check the value being set against the id of the Owner object as well, and skip setting Owner to null if they are the same.

Admittedly, the cause of my problem may not be the same for everyone, but this is at least a cautionary tale to double-check what is happening when your objects are being initialized during deserialization.

Upvotes: 23

I4V
I4V

Reputation: 35353

I don't know how you are trying to deserialize, but this should work....

string json = "{\"Ad\":{\"Type\":\"Request\",         \"IdAd\":\"[email protected]\",         \"Category\":\"cat\",         \"SubCategory\":\"subcat\"},\"Position\":{\"Latitude\":\"38.255\",              \"Longitude\":\"1.2\",              \"Imei\":\"0123456789\"}}";
var obj = JsonConvert.DeserializeObject<RootObject>(json);

public class Ad
{
    public string Type { get; set; }
    public string IdAd { get; set; }
    public string Category { get; set; }
    public string SubCategory { get; set; }
}

public class Position
{
    public string Latitude { get; set; }
    public string Longitude { get; set; }
    public string Imei { get; set; }
}

public class RootObject
{
    public Ad Ad { get; set; }
    public Position Position { get; set; }
}

Upvotes: 8

Related Questions