parse an array as a Json string using DataContractJsonSerializer WP7

荒凉一梦 提交于 2019-12-22 10:53:58

问题


How can I parse the elements of an array in a Json string using DataContractJsonSerializer? The syntax is:

{
   "array":[
 {
  "elementsProperies":"SomeLiteral"
 }
 ]
}

回答1:


You wouldn't necessarily "parse" a json string using DataContractJsonSerializer, but you can deserialize it into an object or list of objects using this. Here is a simple way to deserialize it to a list of objects if this is what you're after.

First you need to have an object type you plan on deserializing to:

[DataContract]
public class MyElement
{
    [DataMember(Name="elementsProperties")] // this must match the json property name
    public string ElementsProperties { get; set; }
}

You can then use something like the following method to deserialize your json string to a list of objects

private List<MyElement> ReadToObject(string json)
{
    var deserializedElements = new List<MyElement>();
    using(var ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
    {
        var ser = new DataContractJsonSerializer(deserializedElements.GetType());
        deserializedElements = ser.ReadObject(ms) as List<MyElement>;
    }
    return deserializedUsers;
}



回答2:


I suggest using Json.net.

In it you would just call:

var jsonObj = JObject.Parse(yourjsonstring);

var elPropertyValue = (string)jsonObj.SelectToken("array[0].elementsProperies");

to get the "SomeLiteral".



来源:https://stackoverflow.com/questions/9034220/parse-an-array-as-a-json-string-using-datacontractjsonserializer-wp7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!