0

I have been on this issue all morning and I cannot figure out what I am doing wrong here.

Here is the XML I am working with.

{
    "item1": "{\"id\":\"53553621-da48-47dd-bad6-6e9d2b3c785f\",\"auth_token\":\"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJDT0VMS0VSQFBPVU5EU0xBQlMuQ09NIiwianRpIjoiZjBlMjI3OTYtMTY4NC00MmRlLWE0ZDYtZDhiYmVlZmRmNmQ2IiwiaWF0IjoxNTg0NTU4ODg5LCJyb2wiOiJhcGlfYWNjZXNzIiwiaWQiOiI1MzU1MzYyMS1kYTQ4LTQ3ZGQtYmFkNi02ZTlkMmIzYzc4NWYiLCJuYmYiOjE1ODQ1NTg4ODgsImV4cCI6MTU4NDU2NjA4OCwiaXNzIjoid2ViQXBpIiwiYXVkIjoiYXBpLm1pbGxtYW5tdWx0aW1lZGlhLmNvbTo0MDQwIn0.dthKzyJRqtkanYNRWEkiqYf4yzQT_A9Qn-GkH5eNAwM\",\"expires_in\":7200}",
    "item2": "105"
}

item1 is a standard auth token I will need to pull and pass to make API calls, I need that auth_token out of there mainly. item2 is a custom field being returned. For some reason it errors out whenever I try to de-serialize this JSON into my object.

public class AuthToken
{
    public string id { get; set; }
    public string auth_token { get; set; }
    public int expires_in { get; set; }
}

public class Token
{
    public AuthToken item1 { get; set; }
    public string item2 { get; set; }
}

Here is the code I am de-serializing with

var t = JsonConvert.DeserializeObject<Token>(token,
                        new JsonSerializerSettings
                        {
                            NullValueHandling = NullValueHandling.Ignore
                        });

Error I am receiving

Newtonsoft.Json.JsonSerializationException: 'Error converting value
ArgumentException: Could not cast or convert from System.String to MyAppName.AuthToken.

Any ideas on what I am doing wrong here?

Nigam Patro
  • 2,760
  • 1
  • 18
  • 33
G_Man
  • 1,323
  • 2
  • 21
  • 33
  • 2
    Can you try this? JSON.NET: https://stackoverflow.com/questions/17584701/json-net-serialize-json-string-property-into-json-object – Oguz Ozgul Mar 18 '20 at 20:01
  • I'm going to be nitpicky. The action "construct an object from -usually- stored data" is called deserialization, serialize is just the opposite. – DrkDeveloper Mar 18 '20 at 20:06
  • Your items are escaped strings so the deserialiser is going to think that it is simply a string value. – David Pilkington Mar 18 '20 at 20:24

1 Answers1

2

The problem is AuthToken isn't a string.

Your token is stored as string literal data.

Edit the source code for make authtoken string (and then convert it to AuthToken), or make the serializer serialize AuthToken data structure.

public class AuthToken
{
    public string id { get; set; }
    public string auth_token { get; set; }
    public int expires_in { get; set; }
}

public class Token
{
    public string item1{get; set;}
    private AuthToken _token;

    public AuthToken AuthToken{ get { return _token ?? _token= new AuthToken(item1);}}
    public string item2 { get; set; }
}

You have to make the AuthToken ctor.

Or you just can create a JsonConverter which makes what you want.

DrkDeveloper
  • 939
  • 7
  • 17