4

I have some JSON I would like to deserialize, but I want to treat one of the properties as a string, not an object.

As an example the JSON looks like this:

{
  "name":"Frank",
  "sex":"male",
  "address": {
               "street":"nowhere st",
               "foo":"bar"
             }
}

And I want to deserialize it to this object - Treating the address object as a string literal:

public class Person
{
   public string name;
   public string sex;
   public string address;
}

I've tried literally deserializing it to this object but get the error:

Cannot deserialize JSON object into type 'System.String'.

Any ideas?

Cheers

Tyler
  • 2,699
  • 4
  • 22
  • 31

1 Answers1

1

The easiest way is if you can modify your Person class and create an Address class for your Address property like:

public class Person
{
   public string name;
   public string sex;
   public Address address;
}

public class Address
{
   public string street; 
   public string foo;
}

This will let JSON.NET deserialize the address object for you.

If you can't modify your class - the solution will need to be handling deserialization of Person manually, I believe.

  • Though it is a solution to this particular example. What if the properties returned differ? And you do not know all possible properties? Then one would want a string still. Technically, this is no answer to the question of the OP. – Mike de Klerk Aug 05 '20 at 10:24