0

我在 Visual Studio 2010 中使用 C# 并创建 WCF 服务。

[
    {
        "QuizCategory":"Basic Skills",
        "QuizID":["1","2"],
        "QuizShortName":["Career","Beginner"]
    },
    {
        "QuizCategory":"General",
        "QuizID":["3","4"],
        "QuizShortName":["General","General # 2"]
    }
]

我在 json 结果中得到上述结果,但我需要显示如下结果,如字典字典:

[
    {
        "QuizCategory":"Basic Skills", 
        Subclasses: 
        [
            {
                "QuizID":1,"QuizShortName":"Career"
            },
            {
                "QuizID":2,
                "QuizShortName":"Beginner"
            }
        ]
    },
    {
        "QuizCategory":"General",      
        Subclasses: 
        [
            {
                "QuizID":3,
                "QuizShortName":"General"
            },
            {
                "QuizID":4,
                "QuizShortName":"General#2"
            }
        ]
    }
] 

StringBuilder jsonResult = new StringBuilder(); 列表 lstCNAInfo = new List();

        using (RestDataContext dc = new RestDataContext())
        {
            CNAClassInfo objCNAInfo;
            var records = dc.GetCNAClasses(Status);

            foreach (var rec in records)
            {
                ArrayList listQID = new ArrayList();
                ArrayList listQSN = new ArrayList();
                String[] splitQID = rec.QuizId.Split(',');
                String[] splitQSN = rec.QuizShortName.Split('$');
                foreach (var varlist in splitQSN)
                {
                    listQSN.Add(varlist);
                }
                foreach (var varlist in splitQID)
                {
                    listQID.Add(varlist);
                }
                objCNAInfo = new CNAClassInfo();
                objCNAInfo.QuizCategory = rec.QuizCat;
                objCNAInfo.QuizID = listQID;
                objCNAInfo.QuizShortName = listQSN;                                        
                lstCNAInfo.Add(objCNAInfo);
            }
        }
        //Json serialzer
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<CNAClassInfo>));
        MemoryStream ms = new MemoryStream();
        serializer.WriteObject(ms, lstCNAInfo);
        jsonResult.Append(Encoding.Default.GetString(ms.ToArray()));
        ms.Close();
        return jsonResult.ToString();
    }
4

1 回答 1

0

如果它像您显示的那样序列化响应仅仅是因为这就是您的类结构的样子。

如果您想获得预期的输出,请确保您的结构如下所示:

public class Category
{
    public string QuizCategory {get;set;}
    public List<Subclasses> {get;set;}
}

public class Subclasses
{
     public int QuizID {get;set;}
     public string QuizShortName  {get;set;}

}

当你序列化它时,你序列化一个List<Category>,每个测验类别将包含一个类别对象。

于 2013-02-11T16:39:15.127 回答