user123
user123

Reputation: 621

ServiceStack DeserializeFromString not settings Fields

I am trying to deserialize a JSON string "{Hints:6}" into a class using ServiceStack.Text. Below is a test case. The problem is that the console prints out 0 instead of 6. So it seems that the 'Hints' Field in 'HintsCount' class is not being set to the new value.

public class HintsCount
{
    public int Hints { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var hintsCount = JsonSerializer.DeserializeFromString<HintsCount>("{Hints:6}");

        Console.WriteLine(hintsCount.Hints);

        Console.ReadLine();
    }
}

Console prints out '0' instead of expected '6'.

Any idea why this is so?

Upvotes: 1

Views: 341

Answers (2)

mythz
mythz

Reputation: 143399

Note this isn't valid JSON:

"{Hints:6}"

JSON requires that all properties names of object literals be quoted, try instead:

"{\"Hints\":6}"

You can just serialize the model to find out what the correct JSON should be, e.g:

new HintsCount { Hints = 6 }.ToJson().Print();

Upvotes: 1

oakio
oakio

Reputation: 1898

Try this:

var hintsCount = JsonSerializer.DeserializeFromString<HintsCount>(@"{""Hints"":6}");

or

var hintsCount = JsonSerializer.DeserializeFromString<HintsCount>("{\"Hints\":6}");

Upvotes: 1

Related Questions