0

我正在使用surveygizmo API 来检索调查回复,但是在他们的JSON 回复(下面的示例)中我遇到了两个问题。

  1. 我将如何遍历问题:答案对,似乎没有与之关联的字段名称,因此我无法执行 JSONObject.getJSONObject("fieldname"); 或 JSONArray.getJSONArray("fieldname"); 由于调查的跳过逻辑,我不知道我需要输入什么问题 ID,所以我也无法通过“问题(#)”获得。

  2. 我需要问题的 questionId,但是鉴于密钥是“[question(#)]”,我将如何获取 questionId,因为我不相信它既不是 JSONObject 也不是 JSONArray,我应该将其视为字符串吗?进行正则表达式搜索以检索“question()”中的#?

JSON响应示例

{
    "result_ok":true,
    "total_count":"1",
    "page":1,
    "total_pages":1,
    "results_per_page":50,
    "data":[{
        "id":"1",
        "contact_id":"",
        "status":"Complete",
        "is_test_data":"1",
        "datesubmitted":"2013-02-07 12:00:00",
        "sResponseComment":"",
        "[question(3)]":"15",
        "[question(4), option(10003)]":"Baseball",
        "[question(4), option(10007)]":"Basketball",
        "[question(4), option(10009)]":"Hockey",
        "[question(12)]":"No",
        "[question(14)]":"Yes",
        "[question(15)]":"Abc",
        "[question(16)]":"No"
   }]
}
4

3 回答 3

2

我一直在做一个类似的项目。这是我到目前为止所拥有的。

模型.cs:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace DeSerializer
{
    [JsonObject]
    public class Responses
    {
        public bool result_ok { get; set; }
        public string total_count { get; set; }
    public int page { get; set; }
    public int total_pages { get; set; }
    public int results_per_page { get; set; }
    public SurveyResponse[] Data { get; set; }
}

[JsonObject]
// Here is the magic: When you see this type, use this class to read it.
// If you want, you can also define the JsonConverter by adding it to
// a JsonSerializer, and parsing with that.
[JsonConverter(typeof(DataItemConverter))]
public class SurveyResponse
{
    public string id { get; set; }
    public string contact_id { get; set; }
    public string status { get; set; }
    public string is_test_data { get; set; }
    public DateTime datesubmitted { get; set; }
    public string sResponseComment { get; set; }
    public List<SurveyQuestion> SurveyQuestions { get; set; }
    public List<SurveyUrl> SurveyUrls { get; set; }
    public List<SurveyGeoData> SurveyGeoDatas { get; set; }
    public List<SurveyVariable> SurveyVariables { get; set; }
    public List<SurveyVariableShown> SurveyVariableShowns { get; set; }
    public List<SurveyQuestionHidden> SurveyQuestionHiddens { get; set; }
    public List<SurveyQuestionOption> SurveyQuestionOptions { get; set; }
    public List<SurveyQuestionMulti> SurveyQuestionMulties { get; set; }
}

public class SurveyQuestion
{
    [Key]
    public int QuestionID { get; set; }
    public string QuestionResponse { get; set; }
}

public class SurveyUrl
{
    [Key]
    public int SurveyUrlID { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }
}

public class SurveyGeoData
{
    [Key]
    public int SurveyGeoDataID { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }
}

public class SurveyVariable
{
    [Key]
    public int SurveyVariableID { get; set; }
    public string Value { get; set; }
}

public class SurveyVariableShown
{
    [Key]
    public int SurveyVariableShownID { get; set; }
    public string Name { get; set; }
    public string Value { get; set; }
}

public class SurveyQuestionHidden
{
    [Key]
    public int QuestionID { get; set; }
    public string QuestionResponse { get; set; }
}

public class SurveyQuestionOption
{
    [Key]
    public int OptionID { get; set; }
    public int QuestionID { get; set; }
    public string QuestionResponse { get; set; }
}

public class SurveyQuestionMulti
{
    [Key]
    public int OptionID { get; set; }
    public int QuestionID { get; set; }
    public string QuestionResponse { get; set; }
}

public class DataItemConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(SurveyResponse);
    }

    public override bool CanRead
    {
        get { return true; }
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var value = (SurveyResponse)existingValue;
        if (value == null)
        {
            value = new SurveyResponse();
            value.SurveyQuestions = new List<SurveyQuestion>();
            value.SurveyUrls = new List<SurveyUrl>();
            value.SurveyGeoDatas = new List<SurveyGeoData>();
            value.SurveyVariables = new List<SurveyVariable>();
            value.SurveyVariableShowns = new List<SurveyVariableShown>();
            value.SurveyQuestionHiddens = new List<SurveyQuestionHidden>();
            value.SurveyQuestionOptions = new List<SurveyQuestionOption>();
            value.SurveyQuestionMulties = new List<SurveyQuestionMulti>();
        }

        // Skip opening {
        reader.Read();

        while (reader.TokenType == JsonToken.PropertyName)
        {
            var name = reader.Value.ToString();
            reader.Read();

            // Here is where you do your magic
            string input = name;

            //[question(1)]
            //[question(11)]
            //[question(111)]
            //[question(1234)]
            //[question(12345)]
            //[url(12345)]
            //[variable(12345)]
            //SINGLE ANSWER
            Match matchSingleAnswer = Regex.Match(input, @"\[(question|calc|comment)\(([0-9]{5}|[0-9]{4}|[0-9]{3}|[0-9]{2}|[0-9]{1})\)]",
                RegexOptions.IgnoreCase);


            //SINGLE VARIABLE
            Match matchSingleVariable = Regex.Match(input, @"\[(variable)\(([0-9]{5}|[0-9]{4}|[0-9]{3}|[0-9]{2}|[0-9]{1})\)]",
                RegexOptions.IgnoreCase);

            //URL
            Match matchUrl = Regex.Match(input, @"\[url",
                RegexOptions.IgnoreCase);

            //GEO DATA
            Match matchGeo = Regex.Match(input, @"\[variable\(""STANDARD_",
                RegexOptions.IgnoreCase);

            //VARIABLES SHOWN
            Match matchVariables = Regex.Match(input, @"\[variable",
                RegexOptions.IgnoreCase);

            //[question(1), option(\"1
            //[question(11), option(\"2
            //[question(111), option(\"1
            //[question(1234), option(\"1
            //[question(12345), option(\"1
            ////////////////////////////////////////////
            ////////The \ values are being removed.
            ////////////////////////////////////////////
            //OPTIONAL ANSWERS
            string myReg = @"\[(question|url|variable|calc|comment)\(([0-9]{5}|[0-9]{4}|[0-9]{3}|[0-9]{2}|[0-9]{1})\),\ option\(""[0-9]";
            Match matchOption = Regex.Match(input, myReg,
                RegexOptions.IgnoreCase);

            //[question(1), option(1
            //[question(11), option(2
            //[question(111), option(1
            //[question(1234), option(1
            //[question(12345), option(1
            //MULTIPLE CHOICE
            Match matchMultiSelect = Regex.Match(input, @"\[question\(([0-9]{5}|[0-9]{4}|[0-9]{3}|[0-9]{2}|[0-9]{1})\),\ option\([0-9]",
                RegexOptions.IgnoreCase);



            //[question(1), option(0)
            //[question(11), option(0)
            //[question(111), option(0)
            //[question(1234), option(0)
            //[question(12345), option(0)
            //HIDDEN
            Match matchHiddenValue = Regex.Match(input, @"\[question\(([0-9]{5}|[0-9]{4}|[0-9]{3}|[0-9]{2}|[0-9]{1})\),\ option\(0\)",
                RegexOptions.IgnoreCase);


            if (matchSingleAnswer.Success)
            {
                int index = int.Parse(name.Substring(10, name.IndexOf(')') - 10));
                SurveyQuestion sq = new SurveyQuestion();
                sq.QuestionID = index;
                sq.QuestionResponse = serializer.Deserialize<string>(reader);
                value.SurveyQuestions.Add(sq);
            }
            else if (matchUrl.Success)
            {
                string urlName = name.Substring(6, name.Length - 9);
                SurveyUrl su = new SurveyUrl();
                su.Name = urlName;
                su.Value = serializer.Deserialize<string>(reader);
                value.SurveyUrls.Add(su);
            }
            else if (matchGeo.Success)
            {
                string geoName = name.Substring(11, name.Length - 14);
                SurveyGeoData sgd = new SurveyGeoData();
                sgd.Name = geoName;
                sgd.Value = serializer.Deserialize<string>(reader);
                value.SurveyGeoDatas.Add(sgd);
            }
            else if (matchSingleVariable.Success)
            {
                int index = int.Parse(name.Substring(10, name.IndexOf(')') - 10));
                SurveyVariable sv = new SurveyVariable();
                sv.SurveyVariableID = index;
                sv.Value = serializer.Deserialize<string>(reader);
                value.SurveyVariables.Add(sv);
            }
            else if (matchVariables.Success)
            {
                string varName = name.Substring(11, name.Length - 14);
                SurveyVariableShown svs = new SurveyVariableShown();
                svs.Name = varName;
                svs.Value = serializer.Deserialize<string>(reader);
                value.SurveyVariableShowns.Add(svs);
            }
            else if (matchHiddenValue.Success)
            {
                int index = int.Parse(name.Substring(10, name.IndexOf(')') - 10));
                SurveyQuestionHidden sqh = new SurveyQuestionHidden();
                sqh.QuestionID = index;
                sqh.QuestionResponse = serializer.Deserialize<string>(reader);
                value.SurveyQuestionHiddens.Add(sqh);
            }
            else if (matchMultiSelect.Success)
            {
                //Multiple choice question selections
                string[] nameArray = name.Split(')');
                string questionPart = nameArray[0];
                string optionPart = nameArray[1];
                int index = int.Parse(questionPart.Substring(10, questionPart.Length - 10));
                int indexSub = int.Parse(optionPart.Substring(9, optionPart.Length - 9));

                SurveyQuestionMulti sqm = new SurveyQuestionMulti();
                sqm.OptionID = indexSub;
                sqm.QuestionID = index;
                sqm.QuestionResponse = serializer.Deserialize<string>(reader);
                value.SurveyQuestionMulties.Add(sqm);

                //NEED TO ADD A BASE QUESTION TO POINT TO ALL THE MULTI
                //SurveyQuestion sq = new SurveyQuestion();
                //sq.QuestionID = sqm.QuestionID;
                //sq.QuestionResponse = "";
                //value.SurveyQuestions.Add(sq);
            }
            else if (matchOption.Success)
            {
                //Optional text value for a given question
                string[] nameArray = name.Split(')');
                string questionPart = nameArray[0];
                string optionPart = nameArray[1];
                int index = int.Parse(questionPart.Substring(10, questionPart.Length - 10));
                int indexSub = int.Parse(optionPart.Substring(10, 5));

                SurveyQuestionOption sqo = new SurveyQuestionOption();
                sqo.OptionID = indexSub;
                sqo.QuestionID = index;
                sqo.QuestionResponse = serializer.Deserialize<string>(reader);
                value.SurveyQuestionOptions.Add(sqo);
            }
            else
            {
                var property = typeof(SurveyResponse).GetProperty(name);
                if (property != null)
                    property.SetValue(value, serializer.Deserialize(reader, property.PropertyType), null);
            }

            // Skip the , or } if we are at the end
            reader.Read();
        }

        return value;
    }

    public override bool CanWrite
    {
        get { return false; }
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}
}

并且,program.cs 文件中的 Main 函数:

            string webReq = String.Empty;

        //Office Energy - Allan Testing
        webReq += "https://restapi.surveygizmo.com/head/survey/xxxxxx";
        webReq += "/surveyresponse/";
        webReq += "?user:pass=xxxxxxxx:xxxxxxx";
        webReq += "&page=101&resultsperpage=1";

        HttpWebRequest request = WebRequest.Create(webReq) as HttpWebRequest;
        var results = String.Empty;
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            StreamReader reader = new StreamReader(response.GetResponseStream());
            results += reader.ReadToEnd();
        }


        Responses responses = new JavaScriptSerializer().Deserialize<Responses>(results);


        Console.WriteLine("FEED HEADERS:");
        Console.WriteLine("");
        Console.WriteLine("result_ok: " + responses.result_ok);
        Console.WriteLine("total_count: " + responses.total_count);
        Console.WriteLine("page: " + responses.page);
        Console.WriteLine("total_pages: " + responses.total_pages);
        Console.WriteLine("results_per_page: " + responses.results_per_page);
        Console.WriteLine("");
        Console.WriteLine("");


        foreach (var item in responses.Data)
        {
            Console.WriteLine("id: " + item.id);
            Console.WriteLine("contact_id: " + item.contact_id);
            Console.WriteLine("status: " + item.status);
            Console.WriteLine("is_test_data: " + item.is_test_data);
            Console.WriteLine("datesubmitted: " + item.datesubmitted);
            Console.WriteLine("sResponseComment: " + item.sResponseComment);
            Console.WriteLine("");
        }

        Console.WriteLine("Press enter to continue...");
        Console.ReadLine();

        //using live stream
        var result = JsonConvert.DeserializeObject<Responses>(results);
        //local results (not using live stream)
        //var result = JsonConvert.DeserializeObject<Responses>(localResults);


        //want to calcualte the highest kay number for the loop
        //http://stackoverflow.com/questions/2805703/good-way-to-get-the-key-of-the-highest-value-of-a-dictionary-in-c-sharp
        //var max = result.Data[0].questions[0].Aggregate((l, r) => l.Key > r.Key ? l : r).Key;


        foreach (var item in result.Data[0].SurveyQuestions)
        {
            string label = "QuestionID = " + item.QuestionID;
            string val = "QuestionResponse = " + item.QuestionResponse;
            Console.WriteLine(label);
            Console.WriteLine(val);
            Console.WriteLine("");


            //Question Option
            var listOptions = result.Data[0].SurveyQuestionOptions;
            var listLocalQuestionOptions = from o in listOptions
                                           where o.QuestionID == item.QuestionID
                                           select o;
            foreach (var itemSub in listLocalQuestionOptions)
            {
                Console.WriteLine("  OPTIONAL");
                string labelSub1 = "  OptionID = " + itemSub.OptionID;
                string labelSub2 = "  QuestionID = " + itemSub.QuestionID;
                string valSub1 = "  QuestionResponse = " + itemSub.QuestionResponse;
                Console.WriteLine(labelSub1);
                Console.WriteLine(labelSub2);
                Console.WriteLine(valSub1);
                Console.WriteLine("");
            }


            //Question Multi
            var listMulties = result.Data[0].SurveyQuestionMulties;
            var listLocalQuestionMulties = from m in listMulties
                                           where m.QuestionID == item.QuestionID
                                           select m;
            foreach (var itemSub in listLocalQuestionMulties)
            {
                Console.WriteLine("MULTIES");
                string labelSub1 = "  OptionID = " + itemSub.OptionID;
                string labelSub2 = "  QuestionID = " + itemSub.QuestionID;
                string valSub1 = "  QuestionResponse = " + itemSub.QuestionResponse;
                Console.WriteLine(labelSub1);
                Console.WriteLine(labelSub2);
                Console.WriteLine(valSub1);
                Console.WriteLine("");
            }


        }

        //Console.WriteLine("");
        //Console.WriteLine("");
        //Console.WriteLine("");
        //Console.WriteLine("");

        //foreach (var item in result.Data[0].SurveyQuestionOptions)
        //{
        //    string label = "OptionID = " + item.OptionID;
        //    string label2 = "QuestionID = " + item.QuestionID;
        //    string val = "QuestionResponse = " + item.QuestionResponse;
        //    Console.WriteLine(label);
        //    Console.WriteLine(label2);
        //    Console.WriteLine(val);
        //    Console.WriteLine("");
        //}

        //Console.WriteLine("");

        Console.WriteLine("Press enter to continue...");
        Console.ReadLine();

        Console.WriteLine("");
        Console.WriteLine("");
        Console.WriteLine("HIDDENS");
        Console.WriteLine("");

        foreach (var item in result.Data[0].SurveyQuestionHiddens)
        {
            string label = "QuestionID = " + item.QuestionID;
            string val = "QuestionResponse = " + item.QuestionResponse;
            Console.WriteLine(label);
            Console.WriteLine(val);
            Console.WriteLine("");
        }



        Console.WriteLine("Press enter to continue...");
        Console.ReadLine();
        Console.WriteLine("");
        Console.WriteLine("");
        Console.WriteLine("MULTIES");
        Console.WriteLine("");

        foreach (var item in result.Data[0].SurveyQuestionMulties)
        {
            string label = "OptionID = " + item.OptionID;
            string label2 = "QuestionID = " + item.QuestionID;
            string val = "QuestionResponse = " + item.QuestionResponse;
            Console.WriteLine(label);
            Console.WriteLine(label2);
            Console.WriteLine(val);
            Console.WriteLine("");
        }



        Console.WriteLine("Press enter to continue...");
        Console.ReadLine();
        Console.WriteLine("");
        Console.WriteLine("");
        Console.WriteLine("URL VALUES");
        Console.WriteLine("");

        foreach (var item in result.Data[0].SurveyUrls)
        {
            string label = "SurveyUrlID = " + item.SurveyUrlID;
            string label2 = "Name = " + item.Name;
            string val = "Value = " + item.Value;
            Console.WriteLine(label);
            Console.WriteLine(label2);
            Console.WriteLine(val);
            Console.WriteLine("");
        }



        Console.WriteLine("Press enter to continue...");
        Console.ReadLine();
        Console.WriteLine("");
        Console.WriteLine("");
        Console.WriteLine("GEO VALUES");
        Console.WriteLine("");

        foreach (var item in result.Data[0].SurveyGeoDatas)
        {
            string label = "SurveyGeoDataID = " + item.SurveyGeoDataID;
            string label2 = "Name = " + item.Name;
            string val = "Value = " + item.Value;
            Console.WriteLine(label);
            Console.WriteLine(label2);
            Console.WriteLine(val);
            Console.WriteLine("");
        }



        Console.WriteLine("Press enter to continue...");
        Console.ReadLine();
        Console.WriteLine("");
        Console.WriteLine("");
        Console.WriteLine("VARIABLES");
        Console.WriteLine("");

        foreach (var item in result.Data[0].SurveyVariables)
        {
            string label = "SurveyVariableID = " + item.SurveyVariableID;
            string val = "Value = " + item.Value;
            Console.WriteLine(label);
            Console.WriteLine(val);
            Console.WriteLine("");
        }



        Console.WriteLine("Press enter to continue...");
        Console.ReadLine();
        Console.WriteLine("");
        Console.WriteLine("");
        Console.WriteLine("VARIABLES SHOWN");
        Console.WriteLine("");

        foreach (var item in result.Data[0].SurveyVariableShowns)
        {
            string label = "SurveyVariableShownID = " + item.SurveyVariableShownID;
            string label2 = "Name = " + item.Name;
            string val = "Value = " + item.Value;
            Console.WriteLine(label);
            Console.WriteLine(label2);
            Console.WriteLine(val);
            Console.WriteLine("");
        }




        Console.WriteLine("");
        Console.WriteLine("Press enter to exit...");
        Console.ReadLine();
于 2013-03-14T16:31:20.450 回答
1

我已经将艾伦的代码放在一个类库中。我们在我工作的公司内部将其用于调查报告工具。它在 Github 上https://github.com/tntp/NSurveyGizmo

于 2015-08-11T15:09:56.083 回答
0

您需要手动解析问题“数字”关键数据。

如果您预计该格式不会有很多可变性,则可以使用正则表达式,或者您可以构建一个简单的“解析器”,以逗号分隔并使用解析的数据构建 POJO。

于 2013-02-15T23:14:08.197 回答