如何解析JSON数据以生成C#示例代码,以演示请求主体对象的创建

时间:2018-08-16 13:26:03

标签: c# json rest api

我需要为各种API编写许多示例代码,这些示例代码演示如何编写代码以使用C#语言使用那些特定的REST API。

现在对于HTTP POST调用的API,首先将请求主体创建为类对象,然后将其序列化为JSON字符串并传递给REST客户端。

我的要求在这一部分中:“ 将请求正文创建为类对象”。

以下示例将使需求变得清晰:-

假设我具有以下JSON数据:

{        
  "workingDays": ["Monday","Wednesday","Friday"],
  "employeeInformation": {
      "employeeID": "12345",
      "name": {
          "firstName": "foo",
          "lastName": "bar"
        }
    },
   "joiningDate":"23061984"
}

我需要解析以上数据并生成以下代码( 目前我正在手动编写 ):

// Create Main Request Body Object
var requestBodyObj = new RequestBody();

// Array Case
var workingDaysObj = new List<string>();
workingDaysObj.Add("Monday");
workingDaysObj.Add("Wednesday");
workingDaysObj.Add("Friday");

requestBodyObj.workingDays = workingDaysObj;

// Nested Object Case
var employeeInformationObj = new employeeInformation();

employeeInformationObj.employeeID = "12345";

var nameObj = new name();
nameObj.firstName = "foo";
nameObj.lastName = "bar";

employeeInformationObj.name = nameObj;

requestBodyObj.employeeInformation = employeeInformationObj;

// Simple Name/Value Pair
requestBodyObj.joiningDate = "23061984";

因此,根据上述示例,JSON数据也可以采用以下两种形式之一(除了简单的名称/值对):

  1. 数组
  2. 嵌套对象

这两种情况都应按上面的代码所示进行处理。

注意::不会向用户提供JSON文件,因此我无法编写任何直接读取JSON文件,反序列化并将其值分配给使用(例如, )的NewtonSoft函数:

// read file into a string and deserialize JSON to a type
Movie movie1 = JsonConvert.DeserializeObject<Movie>(File.ReadAllText(@"c:\movie.json"));

// deserialize JSON directly from a file
using (StreamReader file = File.OpenText(@"c:\movie.json"))
{
    JsonSerializer serializer = new JsonSerializer();
    Movie movie2 = (Movie)serializer.Deserialize(file, typeof(Movie));
}

我只想要一个简单的“ JSON解析器和C#代码生成器”(最好使用C#语言编写)。

任何建议或指示,将不胜感激。

1 个答案:

答案 0 :(得分:0)

Edit Update

  • Pascal Case setting for variable names
  • Json Object names can be mapped to Project model classes
  • Write the output to text file for easy copy

Updated Code Below:-

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;

namespace SampleCodeCreator
{
    class Program
    {
        // Declaring the variables
        static string jsonFilePath = @"[Your File Path]";
        static string outputFilePath = @"[Your File Path]";
        static string  jsonData;
        static Dictionary<string, string> classMap = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);        

        static void Main(string[] args)
        {            
            // Initializing Class map which is used to map the json object to Project Model Class
            InitializeClassMap();

            // clear current data in the output file
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(outputFilePath, false))
            {
                file.Write(String.Empty);
            }

            // read the json data file and store the data in a simple string
            using (StreamReader r = new StreamReader(jsonFilePath))
            {
                jsonData = r.ReadToEnd();                
            }

            // Call the method for the whole json data
            PrintJsonObject("RequestBody", jsonData);            
        }        

        static void PrintJsonObject(string parentObject, string jsonData)
        {
            // if the parent object has any mapped class, then set the object name
            parentObject = MappedClass(parentObject);

            Console.WriteLine("var {0}Obj = new {1}();", ToCamelCase(parentObject), parentObject);
            SetOutput("var " + ToCamelCase(parentObject) + "Obj = new " + parentObject + "();");
            Console.WriteLine("");
            SetOutput("");


            // Deserialize the Json data and iterate through each of its sub-sections
            var jsonSubData = JsonConvert.DeserializeObject<Dictionary<string, object>>(jsonData);
            foreach (var data in jsonSubData)
            {
                var dataKey = data.Key;
                var dataValue = data.Value;

                // array case (if the sub element is an array)
                if (dataValue.ToString().Contains("["))
                {
                    PrintArrayCase(dataKey, dataValue);

                    Console.WriteLine("{0}Obj.{1} = {1}Obj;", ToCamelCase(parentObject), dataKey);
                    SetOutput(ToCamelCase(parentObject) + "Obj." + dataKey + " = " + dataKey + "Obj;");

                    Console.WriteLine("");
                    SetOutput("");

                }
                // nested object case (if the sub element itself contains another json format body)
                else if (dataValue.ToString().Contains("{"))
                {
                    // Recursive Call
                    PrintJsonObject(dataKey, dataValue.ToString());

                    Console.WriteLine("{0}Obj.{1} = {1}Obj;", ToCamelCase(parentObject), dataKey);
                    SetOutput(ToCamelCase(parentObject) + "Obj." + dataKey + " = " + dataKey + "Obj;");

                    Console.WriteLine("");
                    SetOutput("");
                }
                // simple key value pair case
                else
                {
                    PrintKeyValuePairCase(parentObject, dataKey, dataValue.ToString());                    
                }
            }            
        }

        static void PrintArrayCase(string key, object obj)
        {
            Console.WriteLine("var {0}Obj = new List<string>();", key);
            SetOutput("var " + key + "Obj = new List<string>();");

            // The array value is split into its values
            // e.g. [abc, def, ghi]  -> [abc] [def] [ghi]
            var valueString = obj.ToString();
            var valueSplitArray = valueString.Split(',');
            for (int k = 0; k < valueSplitArray.Count(); k++)
            {
                string listValue = "";
                if (k != valueSplitArray.Count() - 1)
                {
                    var startIndex = valueSplitArray[k].IndexOf("\"");
                    listValue = valueSplitArray[k].Substring(startIndex + 1, valueSplitArray[k].Length - startIndex - 2);
                }
                else
                {
                    var startIndex = valueSplitArray[k].IndexOf("\"");
                    listValue = valueSplitArray[k].Substring(startIndex + 1, valueSplitArray[k].Length - startIndex - 5);
                }

                // each value is then added to the main list object
                Console.WriteLine(@"{0}Obj.Add(""{1}"");", ToCamelCase(key), listValue);
                SetOutput(@""+ToCamelCase(key)+@"Obj.Add("""+listValue+@""");");
            }

            Console.WriteLine("");
            SetOutput("");
        }

        static void PrintKeyValuePairCase(string parentObj, string key, string value)
        {
            Console.WriteLine("{0}Obj.{1} = \"{2}\";", ToCamelCase(parentObj), key, value);
            SetOutput("" + ToCamelCase(parentObj) + "Obj." + key + " = \"" + value + "\";");
        }

        static string ToCamelCase(string str)
        {
            if (!String.IsNullOrEmpty(str))
            {
                return str.Substring(0, 1).ToLower() + str.Substring(1, str.Length - 1);
            }
            else
            {
                return null;
            }
        }

        static string MappedClass(string str)
        {
            if (classMap.ContainsKey(str))
                return classMap[str];
            else
                return str;
        }

        static void InitializeClassMap()
        {
            classMap.Add("employeeInformation", "EmployeeInfo");            
        }

        static void SetOutput(string str)
        {
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(outputFilePath, true))
            {
                file.WriteLine(str);
            }
        }
    }
}