使用DataContractJsonSerializer WP7将数组解析为Json字符串 [英] parse an array as a Json string using DataContractJsonSerializer WP7

查看:164
本文介绍了使用DataContractJsonSerializer WP7将数组解析为Json字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用DataContractJsonSerializer解析Json字符串中数组的元素? 语法为:

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

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

推荐答案

您不必使用DataContractJsonSerializer来解析"一个json字符串,但是您可以使用它反序列化为一个对象或对象列表.如果您要这样做,这是一种将其反序列化为对象列表的简单方法.

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; }
}

然后您可以使用类似以下方法的方法将json字符串反序列化为对象列表

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;
}

这篇关于使用DataContractJsonSerializer WP7将数组解析为Json字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆