简体   繁体   English

servicestack.text将数组反序列化为对象

[英]servicestack.text deserializing array to object

I have a REST-Service build with ServicStack and in one call the user can send different types of values. 我有一个使用ServicStack的REST-Service构建,在一次调用中,用户可以发送不同类型的值。 So I made the property in C# of type object. 所以我在C#类型对象中创建了属性。

The JSON that is sent looks like this: 发送的JSON如下所示:

{"name":"ffff","params":[{"pId":1,"value":[624,625]},{"pId":2,"value":"xxx"}]}

The part "value":[624,625] results in a string object filled with "[624,625]". 部分“值”:[624,625]导致字符串对象填充“[624,625]”。 I was hoping to get an int-array or at least a string array, but it is plain string. 我希望得到一个int数组或至少一个字符串数组,但它是纯字符串。 I set JsConfig.TryToParsePrimitiveTypeValues = true, but that doesn't seem to have any effect. 我设置JsConfig.TryToParsePrimitiveTypeValues = true,但这似乎没有任何效果。

I tried the latest sources from github. 我尝试了github的最新资源。

Can this be done with any combination of switches or must I parse this myself? 这可以通过任何开关组合完成,还是我必须自己解析?

Thanks 谢谢

EDIT: 编辑:

Here is some testcode: 这是一些测试代码:

[TestMethod]
public void JsonTest()
{
    string json = "{\"name\":\"ffff\",\"params\":[{\"pId\":1,\"value\":[624,625]},{\"pId\":2,\"value\":\"xxx\"}]}";

    var x = JsonSerializer.DeserializeFromString<xy>(json);
    Assert.AreEqual(x.Params[0].Value.GetType(), typeof(int[]));
}

public class xy
{
    public string Name { get; set; }

    public List<Param> Params { get; set; }
}

public class Param
{
    public int PId { get; set; }

    public object Value { get; set; }
}

If you change the type of "Value" to int array as follows, then ServiceStack will serialize to array of int. 如果您将“Value”的类型更改为int数组,则ServiceStack将序列化为int数组。

    public class Param
    {
        public int PId { get; set; }

        public int[] Value { get; set; }
    }

The following unit test passes: 以下单元测试通过:

    [TestMethod]
    public void JsonTest()
    {
        string json = "{\"name\":\"ffff\",\"params\":[{\"pId\":1,\"value\":[624,625]},{\"pId\":2,\"value\":\"xxx\"}]}";

        var x = JsonSerializer.DeserializeFromString<xy>(json);
        Assert.AreEqual(x.Params[0].Value.GetType(), typeof(int[]));
        // Show that we have some integers
        Assert.IsTrue(x.Params[0].Value.Count()>0);
    }

If you cannot change the type of Value for any reason, then you can use ServiceStack.Text to serialize the string into an array as needed. 如果由于任何原因无法更改Value的类型,则可以根据需要使用ServiceStack.Text将字符串序列化为数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM