为什么这个json c#-Object序列化错误

时间:2011-12-07 09:03:22

标签: c# json

我是json和c#的新手,需要正确方向的帮助 看下面的图片,你会看到json字符串看起来很滑稽。

如果这是错误的话,如何删除斜杠或我应该使用哪种解析器

这是我的C#代码:

 PostList p = new PostList();

 Posts posts1 = new Posts();
 posts1.username = "aaaa";
 posts1.message = "hej again";
 posts1.time = "time1";
 p.setPost(posts1);

 Posts posts2 = new Posts();
 posts2.username = "bbbb";
 posts2.message = "hej again again";
 posts2.time = "time2";
 p.setPost(posts2);

 Posts posts3 = new Posts();
 posts3.username = "cccc";
 posts3.message = "hej again again agin";
 posts3.time = "time3";
 p.setPost(posts3);
 System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(p.GetType());
 MemoryStream ms = new MemoryStream();
 serializer.WriteObject(ms, p);
 string json = Encoding.Default.GetString(ms.ToArray());

这是我尝试序列化的课程

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Specialized;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace Project2
{
    [DataContract]
    public class PostList
    {
        [DataMember]
        private List<Posts> posts { get; set; } 

        public PostList(){

            this.posts = new List<Posts>();
        }


        public List<Posts> getPostContainterList()
        {
            return posts;
        }

        public void setPost(Posts post)
        {
            posts.Add(post);
        }
    }

    [DataContract]
    public class Posts
    {
        [DataMember]
        public String message { get; set; }

        [DataMember]
        public String time { get; set; }

        [DataMember]
        public String username { get; set; }
    }
}

enter image description here

显示来自的字符串的更新 enter image description here

1 个答案:

答案 0 :(得分:2)

使用Fiddler / Chrome工具/ IE f12开发人员工具点击您的服务,查看原始响应。我怀疑你的JSON实际上很好,并且你使用的JSON查看器添加了斜杠。

如果您是JSON的新用户,那么粘贴长JSON字符串并按层次结构查看它们的快速资源是jsonlint.com。它也验证了它们。

相关问题