2017-03-01 91 views
1

在此处提供了一些解决方案之后,我选择了使用NewtonSoft。但我无法将JSON转换为类对象。我认为,json(或字符串)以不正确的格式传递给方法。如何将JSON类似字符串转换为C#对象

类:

public class EmailAPIResult 
{ 
    public string Status { get; set; } 
} 

方法:

//....code 
using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) 
{ 
    string result = streamReader.ReadToEnd(); 
    //when hovered on "result", the value is "\"{\\\"Status\\\":\\\"Success\\\"}\"" 
    //For Text Visualizer, the value is "{\"Status\":\"Success\"}" 
    //And for JSON Visualizer, the value is [JSON]:"{"Status":"Success"}" 

    EmailAPIResult earesult = JsonConvert.DeserializeObject<EmailAPIResult>(result);  
    //ERROR : Error converting value "{"Status":"Success"}" to type 'EmailAPIResult'. 
} 

下面的代码工作:

using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) 
    { 
     string good = "{\"Status\":\"Success\"}"; 
     //when hovered on "good", the value is "{\"Status\":\"Success\"}" 
     //For Text Visualizer, the value is {"Status":"Success"} 
     //And for JSON Visualizer, the value is 
     // [JSON] 
     //  Status:"Success" 

     EmailAPIResult earesult = JsonConvert.DeserializeObject<EmailAPIResult>(good); //successful 
    } 

我应该如何格式化 “结果”,让我代码有效。

+0

http://json2csharp.com/ –

+0

你甚至不写如何你的JSON文件看起来像?!? –

+0

也许你的'httpResponse'为空 –

回答

1

虽然这是真的,你可以修复你的字符串,就像m.rogalski建议,我会推荐而不是来做到这一点。

正如你说:

的 “结果” 徘徊时,该值是 “\”{\\\ “状态\\\”:\\\ “成功\\\”} \” “

我建议检查它来自哪里。什么是你的后端实现?看起来好像您的HTTP答案的JSON结果实际上不是JSON,而是完全转义的JSON字符串。 如果您可以控制后端发生的事情,那么您应该真正修复它,因为每次尝试将客户端写入HTTP服务时都会出现类似问题。

无论如何,如果希望速战速决,尝试之一:

result = result.Replace(@"\\", @"\").Replace(@"\""", "\"").Trim('\"'); 

来电来Replace与转义替换原有的转义字符。 Trim修剪前导和尾随引号。

+0

这是正确的。 HTTP的结果实际上并不是JSON,我不能控制它。 – Qwerty

+0

太可惜了。然后快速修复就足够了。 –

+0

我想避免做'if(result.Contains(“success”))'。非常感谢你。那工作!!。 – Qwerty

0

正如你在你的问题已经证明:

的 “结果” 徘徊时,该值是 “\”{\\ “状态\\”:\\ “成功\\”} \ “”

这意味着你的JSON字符串的起始和转义字符"结束。

试图摆脱这些像这样的(例如):

string result = streamReader.ReadToEnd(); 
result = result.Substring(1); 
result = result.Substring(0, result.Length - 1); 

,这将给你喜欢"{\\\"Status\\\":\\\"Success\\\"}"

编辑值: 结果我已是无效的(我坏),因为它包含另一个非转义字符,它是\。你可以摆脱这种使用string.Replace方法:

result = result.Replace("\\", string.Empty); 

但这些替代品的缺点是,如果您的JSON将包含该字符,它会被空(\0)字符替换

// {"Status":"Some\Other status"} 
// would become 
// {"Status":"SomeOther status"} 
+0

它现在给出了一个不同的错误'无效的属性标识符字符:\'。在悬停'result'时,值就是你所提到的。对于Text Visualizer,值为'{\“Status \”:\“Success \”}',对于JSON可视化器,它表示string不是json格式。 – Qwerty

相关问题