Json.net格式

时间:2014-02-28 14:49:22

标签: c# json json.net

我在api电话的json编队方面遇到了麻烦。我需要这样的东西

{
    "token": "87dd8f93-27ad-493c-8ab1-e75c50b8fb71",
    "answers": [
        {
            "question": "Where are you from",
            "ans": "t"
        },
        {
            "question": "I am from tts",
            "ans": "f"
        }
    ]
}

我有一系列名为答案的哈希,我用

之类的东西单独制作
string json = JsonConvert.SerializeObject(account, Formatting.Indented);

之后我必须使用令牌,但后来​​使用相同的过程

{
    "token": "87dd8f93-27ad-493c-8ab1-e75c50b8fb71",
    "answers": [
        "{\r\n
            \"question\": \"Where are you from\",
            \"ans\": \"t\"
        }",
        "{\r\n
            \"question\": \"I am from tts\",
            \"ans\": \"f\"
        }"
    ]
}

 public class Account
    {
       public string question { get; set; }
       public string ans { get; set; }           
    }

之后

if (ansNo.IsChecked == true)
                    {
                        Account account = new Account
                        {
                            question = quizText.Text,
                            ans = "f"
                        };
                        string json = JsonConvert.SerializeObject(account, Formatting.Indented);
                        Globals.answers[counter] = json;   
                    }
                    else
                    {
                        Account account = new Account
                        {
                            question = quizText.Text,
                            ans = "t"
                        };
                        string json = JsonConvert.SerializeObject(account, Formatting.Indented);
                        Globals.answers[counter] = json;
                    }

请帮助 感谢

1 个答案:

答案 0 :(得分:1)

我认为通过重新调整数据可以实现您所追求的目标。创建一个要序列化的新对象以返回

public class MyJson{
    public string token {get;set;}
    public List<Account> answers {get;set;}

    public MyJson(){
        answers = new List<Account>();
    }
}

创建一个新的MyJson对象并添加令牌

MyJson o = new MyJson { token = "87dd8f93-27ad-493c-8ab1-e75c50b8fb71" }

然后就像你已经添加到列表的答案

Account account = new Account{
     question = quizText.Text,
     ans = "t"
};
o.answers.Add(account);

然后序列化整个事物并将其返回

return JsonConvert.SerializeObject(o, Formatting.Indented);