سؤال

Perhaps I am doing this wrong, but I have the following test which is failing:

[Test]
public void Can_Deserialize_List()
{
    string json = @"
    {
        ""a"": [
            {
                ""b"":1,
                ""c"":false
            },{
                ""b"":2,
                ""c"":true
            }
        ]
    }";

    JsonObject container = JsonSerializer.DeserializeFromString<JsonObject>(json);
    List<JsonObject> aList = JsonSerializer.DeserializeFromString<List<JsonObject>>(container["a"]);
    Assert.True(aList.Count == 2);
    Assert.True(aList[0]["b"] == "1");
    Assert.True(aList[0]["c"] == "false");
    Assert.True(aList[1]["b"] == "2");
    Assert.True(aList[1]["c"] == "true");
}

Is this a bug in service stack? Or a misunderstanding on my part? If it is a misunderstanding, then how would I go about doing what I am doing correctly?

هل كانت مفيدة؟

المحلول

I solved it by rewriting the code as follows:

[Test]
public void Can_Deserialize_List()
{
    string json = @"
    {
        ""a"": [
            {
                ""b"":1,
                ""c"":false
            },{
                ""b"":2,
                ""c"":true
            }
        ]
    }";

    JsonObject container = JsonObject.Parse(json);
    JsonArrayObjects aList = container.ArrayObjects("a");
    Assert.True(aList.Count == 2);
    Assert.True(aList[0]["b"] == "1");
    Assert.True(aList[0]["c"] == "false");
    Assert.True(aList[1]["b"] == "2");
    Assert.True(aList[1]["c"] == "true");
}

It looks like JsonObject uses JSV formatting internally, and you shouldn't expect that string values to be in JSON format. Instead you should use the JsonObject.Object and JsonObject.ArrayObjects methods to get internal objects/arrays.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top