我有一个数据交换框架,数据将被格式化为JSON,以便使用http从服务器传递给客户端。
这是'基本结构:
sql = 'update Atm set Balance=%s Where ID=%s'%(str(rollingBalance),str(ID))
或:
{
status: 0,
data: {name:"balbala",age:12}
msg: "OK"
}
或者发生错误的事情:
{
status: 0,
data: [{name: "balbalba", age:12},{name:"another balbala", age:13}],
msg: "OK"
}
我们的基本想法是使用{
status: -1,//the error code
msg: "Sorry, internal error"
}
作为错误代码,并在执行更多操作之前检查错误代码,当不是status
时,只显示0
这是详细信息错误的信息,但在msg
字段中我们想要携带任意JSON格式,主要是data
和array
,我们可以在java中使用object(key-values)
实现这一点,但是来到gson
我们不知道如何做到这一点,有没有办法用C#
做到这一点?
这是我目前实现的,但有一些错误。
c#
这是错误:
//the Response structure Definition.
public class Respose
{
public int status;
public object data;
public string msg;
public Respose() { }
}
//serialize the HTTP text first time to a Response structure.
Respose resp = JsonConvert.DeserializeObject<Respose>(infoStr);
//just check the status shutcut the processing when meet with a non-zero err-code
if(resp.status != 0)
{
Debug.LogWarning(resp.msg);
yield break;
}
//getting the data as json string so that we could deserialize it again
string levelArrayStr = JsonConvert.SerializeObject(resp.data);
//the real data-load we need.
List<Level> levelsFromServer = JsonConvert.DeserializeObject<List<Level>>(levelArrayStr);
答案 0 :(得分:0)
您可以使用两个(或三个)单独的类进行反序列化,也可以使用JObject
。
public class Data
{
public string Name;
public int Age;
}
const string SINGLE = @"{
status: 0,
data: {name: ""balbala"",age:12},
msg: ""OK""
}";
const string MULTI = @"{
status: 0,
data: [{name: ""balbala"",age:12},{name: ""another balbala"",age:13}],
msg: ""OK""
}";
const string ERROR = @"{
status: 1,
msg: ""Sorry, internal error""
}";
List<Data> loDataList = new List<Data>();
//JObject loJObject = JObject.Parse(ERROR);
//JObject loJObject = JObject.Parse(SINGLE);
JObject loJObject = JObject.Parse(MULTI);
if (loJObject.Value<int>("status") != 0)
{
Debug.WriteLine(loJObject.Value<string>("msg"));
return;
}
JToken loDataToken = loJObject["data"];
switch (loDataToken.Type)
{
case JTokenType.Object:
loDataList.Add(loJObject["data"].ToObject<Data>());
break;
case JTokenType.Array:
loDataList = loJObject["data"].ToObject<List<Data>>();
break;
}
foreach (var loData in loDataList)
{
Debug.WriteLine("Name: {0} Age: {1}", loData.Name, loData.Age);
}