将 JSON 反序列化为对象
我收到 JSON,我需要反序列化。我正在使用 JavaScriptSerializer 来执行此操作。
物体
class Player
{
public string name{ set; get; }
public float yPos { set; get; }
public float xPos { set; get; }
}
class Communication
{
public string id{ set; get; }
public string message{ set; get; }
public string status{ set; get; }
}
例如 JSON:
var json1 = "[{\"name\":\"Master\",\"xPos\":\"34.67\",\"yPos\":\"85.36\"}, {\"name\":\"Puppet\",\"xPos\":\"19.56\",\"yPos\":\"75.19\"}]";
var json2 = "[{\"id\":\"5697862\",\"message\":\"Hello\",\"status\":\"85.36\"}, {\"id\":\"4698458\",\"message\":\"Hi\",\"status\":\"75.19\"}]";
反序列化器方法:
private static List<T> Deserialize<T>(string json)
{
var s = new System.Web.Script.Serialization.JavaScriptSerializer();
List<T> obj = s.Deserialize<List<T>>(json);
return obj;
}
但问题是我收到了两种不同类型的 JSON 消息。那么我如何找出需要反序列化的对象呢?
I'm receiving JSON, that i need to Deserialize. I'm using JavaScriptSerializer to do so.
E.g. Objects
class Player
{
public string name{ set; get; }
public float yPos { set; get; }
public float xPos { set; get; }
}
class Communication
{
public string id{ set; get; }
public string message{ set; get; }
public string status{ set; get; }
}
E.g. JSONs:
var json1 = "[{\"name\":\"Master\",\"xPos\":\"34.67\",\"yPos\":\"85.36\"}, {\"name\":\"Puppet\",\"xPos\":\"19.56\",\"yPos\":\"75.19\"}]";
var json2 = "[{\"id\":\"5697862\",\"message\":\"Hello\",\"status\":\"85.36\"}, {\"id\":\"4698458\",\"message\":\"Hi\",\"status\":\"75.19\"}]";
Deserializer Method:
private static List<T> Deserialize<T>(string json)
{
var s = new System.Web.Script.Serialization.JavaScriptSerializer();
List<T> obj = s.Deserialize<List<T>>(json);
return obj;
}
But here is the problem I have two different kind of JSON messages coming. So how do I figure out to what object I need to Deserialize?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以动态处理结果,而不是反序列化到特定的类
Instead of deserializing to a specific class you can process the result dynamically
我建议查看 DataContractJsonSerializer (它也可以反序列化) 。此类可确保您在分别对 JSON 进行序列化和反序列化时遵循特定的约定。
对于反序列化,它的工作原理如下:
序列化的工作原理如下:
请参阅链接以获取更多说明。
I would recommend taking a look at the DataContractJsonSerializer (which can also deserialize). This class ensures that you are following the specific contract when you serialize and deserialize to and from JSON, respectively.
For deserialization, it works something like this:
Serialization works like this:
See the link for additional explanation.