将字符串转换为Object C#

时间:2017-05-03 06:43:49

标签: c# json json.net

我的问题很简单,当我使用

时,我必须用它来转换json字符串
jsonstring = "{"message":"success","ID": "[83689707,83689708]"}"
var obj = JsonConvert.DeserializeObject<jsonResponseMail>(jsonstring);

我尝试这个对象,但转换失败:(

public class jsonResponseMail
    {
        public string message { get; set; }
        public List<int> ID { get; set; }
    }

  public class jsonResponseMail
    {
        public string message { get; set; }
        public List<string> ID { get; set; }
    }

   public class jsonResponseMail
    {
        public string message { get; set; }
        public int[] ID { get; set; }
    }

    public class jsonResponseMail
    {
        public string message { get; set; }
        public string[] ID { get; set; }
    }

2 个答案:

答案 0 :(得分:2)

鉴于你的字符串,它应该是

public class jsonResponseMail
{
    public string message { get; set; }
    public string ID { get; set; }
}

如果您期望列表,那么字符串将是

{"message":"success","ID": [83689707,83689708]}

和班级将是

public class jsonResponseMail
{
    public string message { get; set; }
    public List<int> ID { get; set; }
}

同样jsonResponseMail也遵守类命名约定。请改用JsonResponseMail

答案 1 :(得分:0)

您需要手动修改JSON字符串。像这样:

var original = JsonConvert.DeserializeObject<JsonResponseMailOriginal>(json);
var ids = original.Id.Replace("[", "").Replace("]", "").Split(',').Select(Int32.Parse).ToList();
var result = new JsonResponseMail()
{
    message = original.message,
    Ids = ids
};