C#, NewtonSoft.json , 转换一个网络服务器返回的字符串,报错:
无法将类型为“System.String”的对象强制转换为类型“Newtonsoft.Json.Linq.JObject”。
字符串内容:"{\"message\":\"上传成功\",\"code\":\"1\"}"
JObject objResp = (JObject)JsonConvert.DeserializeObject(resp);
解决方法:用JsonReader对原始字符串进行处理
JsonReader reader = new JsonTextReader(new StringReader(resp));
while (reader.Read())
//JSON读取:String System.String {"message":"上传成功","code":"1"}
Console.WriteLine("JSON读取:" + reader.TokenType + "\t\t" + reader.ValueType + "\t\t" + reader.Value);
resp = reader.Value.ToString();
Console.WriteLine("处理后:" + resp);
处理之后的内容:{"message":"上传成功","code":"1"}
C#, NewtonSoft.json , 转换一个网络服务器返回的字符串,报错:无法将类型为“System.String”的对象强制转换为类型“Newtonsoft.Json.Linq.JObject”。字符串内容:"{\"message\":\"上传成功\",\"code\":\"1\"}"代码:JObject objResp = (JObject)JsonConvert.Deserializ...
1、问题描述
C#使用
Newton
soft
.
Json
将 一般
对象
序列化和反序列化为
json
时,一般使用 Serialize
Object
() 和 Deserialize
Object
() 即可。
但是,当
对象
中包含一个自定义集合
对象
时,仅仅使用Deserialize
Object
()
无法
正确实现反序列化。
有可能报错:
无法
将
类型
为“
Newton
soft
.
Json
.
Linq
.J
Object
”的
对象
强制转换
2、代码说明
直接用一段示例代码,进行说明。
2.1 准备阶段
示例准备3个类:
Action 类:
今天在做项目的时候,无意间犯了一个错误,出现了:
无法
将
类型
为“System.DBNull”的
对象
强制转换
为
类型
“System.
String
”。的错误提示。想着很多的初学者可能会遇上同样的问题,现在分析出现的问题,并解决之。
问题:用强
类型
DataSet 获取Oracle数据,其中一个字段值为DBNull,报错:
无法
强制转换
成
String
。
详细错误信息如下所示:
无法
将
类型
为“Syste
问题场景:使用Dictionary处理
Json
数据,取出值
//第一种
Dictionary<
string
,
string
> dic = new Dictionary<
string
,
string
>();
dic.Add("id", "i1");
dic.Add("2id", "i2");
var serializer = new JavaScriptSerializer();
//将
object
对象
转换为字符
var
json
= serializer.Serialize(dic
psql中varchar
类型
的
json
数据也可手动转成
json
格式再对
json
格式的数据进行解析,示例语句如下:
SELECT A
.log ::
json
-> 'des' :: TEXT
areastable A
SELECT
SELEC
使用
Newton
soft
.
Json
的时候 vs 编译出现错误:
Severity Code Description Project File Line
Error Unhandled Exception: System.TypeLoadException: Could not load type '
Newton
soft
.
Json
.
Linq
.JCon
C#项目中使用
Newton
Soft
.
json
,报错提示:
Can not add
Newton
soft
.
Json
.
Linq
.JValue to
Newton
soft
.
Json
.
Linq
.J
Object
.
代码如下:
//{"code":200,"检测编号":"JC1810231520411","message":"OK"}
string
resp = ...
J
Object
respObj...