微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有一个使用ServicStack的REST-Service构建,在一次调用中,用户可以发送不同类型的值.所以我在C#类型对象中创建了属性.

发送的JSON如下所示:

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

部分“值”:[624,625]导致字符串对象填充“[624,625]”.我希望得到一个int数组或至少一个字符串数组,但它是纯字符串.
我设置JsConfig.TryToParsePrimitiveTypeValues = true,但这似乎没有任何效果.

我尝试了github的最新资源.

这可以通过任何开关组合完成,还是我必须自己解析?

谢谢

编辑:

这是一些测试代码

[TestMethod]
public void Jsontest()
{
    string json = "{\"name\":\"ffff\",\"params\":[{\"pId\":1,\"value\":[624,{\"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; }
}

解决方法

如果您将“Value”的类型更改为int数组,则ServiceStack将序列化为int数组.

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

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

以下单元测试通过:

[TestMethod]
    public void Jsontest()
    {
        string json = "{\"name\":\"ffff\",\"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);
    }

如果由于任何原因无法更改Value的类型,则可以根据需要使用ServiceStack.Text将字符串序列化为数组.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐