bitshift
bitshift

Reputation: 6842

JsonConvert.DeserializeObject results in null values of object

I'm passing some JSON from one Web API to another. Within the 1st API I serialize the object, and the resulting string looks fine. When the call comes into the 2nd API, I'm stepping through the method at the point of deserializing the JSON into an object.

Inside the receiving controller:

string inputs = req.Content.ReadAsStringAsync().Result;

JSON string (inputs variable) looks like this: (yes this is viewed within the Text visualizer):

{"LogEntry":"{\"Id\":0,\"AppName\":\"MyTestController\",\"LogMessage\":\"this is a test\",\"ServerName\":\"dev-test3\",\"LoggedOnDate\":\"2017-06-27T15:37:28.1691783-05:00\",\"LogType\":1}"}

Now after I attempt to deserialize the JSON back into my object (LogEntry) using this:

LogMgr.LogEntry logentry = JsonConvert.DeserializeObject<LogMgr.LogEntry>(inputs);

I am getting null values in the fields of LogEntry.

Here is my POCO class LogEntry:

public class LogEntry
{
    public int Id { get; set; }
    public string AppName { get; set; }
    public string LogMessage { get; set; }
    public string ServerName { get; set; }
    public DateTime LoggedOnDate { get; set; }
    public int LogType { get; set; }
}

Something has gone wrong, but I can't see it. Seems like I've had issues with escape characters in JSON data before.

What can I check for in the deserialization step?

Upvotes: 0

Views: 999

Answers (1)

Brian Rogers
Brian Rogers

Reputation: 129667

There are two problems here.

  1. It looks to me like your first API is double-serializing the log entry. Most likely this is happening because you are manually serializing the entry somewhere inside your controller method, then inserting the JSON string into another object, and then Web API is automatically serializing that object when you return it from the method (as it was designed to do), resulting in the double-serialized log entry.

  2. On the other end, you are trying to deserialize this JSON into a LogEntry class, but you are not accounting for the wrapper object around it. Since all the data is one level down in the JSON, it does not match up with the class you are trying to deserialize into and everything ends up being null.

The best way to fix the problem is to change the first API such that it does not manually serialize the log entry, and then just returns it directly without wrapping it in another object. If you do that, then you should end up with JSON that looks like this:

{
  "Id": 0,
  "AppName": "MyTestController",
  "LogMessage": "this is a test",
  "ServerName": "dev-test3",
  "LoggedOnDate": "2017-06-27T15:37:28.1691783-05:00",
  "LogType": 1
}

and that should deserialize into your LogEntry class just fine.

Upvotes: 2

Related Questions