Нужна помощь в записи данных в JSON в C # - PullRequest
0 голосов
/ 16 мая 2018

Я перебираю некоторые данные и пытаюсь записать скопированные данные в файл json, используя c # newtonsoft.Json.

Я застреваю при записи данных в файл Json на моем контроллере . Многомерные массивы в c # смущают меня.

Заранее спасибо.

Это пример файла Json, который я пытаюсь создать:

[
{
    "testmodule1": {
        "name": {
            "required": true,
            "options": [
                "option1",
                "option2"
            ]
        },
        "admin": {
            "required": true,
            "options": [
                "option1",
                "option2"
            ]
        },
        "path": {
            "required": true,
            "options": [
                "option1",
                "option2"
            ]
        }
    }
},
{
    "testmodule2": {
        "name": {
            "required": true,
            "options": [
                "option1",
                "option2"
            ]
        },
        "server": {
            "required": false,
            "options": [
            ]
        },
        "port": {
            "required": true,
            "options": [
                "option1",
                "option2"
            ]
        }
    }
}
]

Это мои занятия:

    public class JsonData
{
    public Dictionary<string, JsonParameters> modulename { get; set; }
}

public class JsonParameters
{
    public JsonParametersData parameter { get; set; }
}
public class JsonParametersData
{
    public bool required { get; set; }
    public List<string> options { get; set; }
}

Это мой контроллер, вот где я застреваю. имя modulename не существует в текущем контексте :

public class WebscrapeController : Controller
    {
        // GET: Webscrape
        public ActionResult Index()
        {

            List<JsonData> data = new List<JsonData>();
            data.Add(new JsonData()
            {
                modulename = new Dictionary<string, JsonParameters>()
                {
                    modulename.Add("testmodule1", new JsonParameters()
                    {
                        parameter = new JsonParametersData()
                        {
                            required = true,
                            options = new List<string>()
                            {
                                "option1",
                                "option2"
                            }
                        }
                    })
                }
            });

            string json = JsonConvert.SerializeObject(data.ToArray());

            //write string to file
            System.IO.File.WriteAllText(
                @"C:mypath",
                json);
        }
    }

enter image description here

Обратите внимание, что имена свойств "testmodule1" и "testmodule2", а также "name", "admin", "path", "server" являются произвольными; они отличаются для каждого массива.

Ответы [ 2 ]

0 голосов
/ 16 мая 2018

Здесь используется другой подход с использованием Newtonsoft JObject.

https://dotnetfiddle.net/TdFDQc

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

namespace StackOverflow
{
public class Program
{
    public static void Main(string[] args)
    {
        JArray array = new JArray();

        // Module 1
        JObject parameter = new JObject();
        AddParameter(parameter, "name", true, new[] { "option1", "option2" });
        AddParameter(parameter, "admin", true, new[] { "option1", "option2" });
        AddParameter(parameter, "path", false, new[] { "option1", "option2", "option3" });

        JObject module = new JObject();
        module.Add("testmodule1", parameter);

        array.Add(module);

        // Module 2
        parameter = new JObject();
        AddParameter(parameter, "name", true, new[] { "option1", "option2" });
        AddParameter(parameter, "server", false, Array.Empty<string>());
        AddParameter(parameter, "port", true, new[] { "option1", "option2", "option3" });

        module = new JObject();
        module.Add("testmodule2", parameter);

        array.Add(module);

        // Display result
        var json = array.ToString();
        Console.WriteLine(json);        
    }

    static void AddParameter(JObject jObject, string name, bool required, string[] options)
    {
        JObject parameterProperties = new JObject();
        parameterProperties.Add("required", JToken.FromObject(required));
        parameterProperties.Add("options", JToken.FromObject(options));

        jObject.Add(name, parameterProperties);
    }
}

}
0 голосов
/ 16 мая 2018

Поскольку имена свойств "testmodule1" и "testmodule2", а также "name", "admin", "path", "server" и "port" являются произвольными и не известны заранее, вам необходимо смоделировать свой * Массив 1008 * как List<Dictionary<string, Dictionary<string, JsonParametersData>>>. Это связано с тем, что при сериализации словаря в JSON с использованием Json.NET ключи словаря становятся именами свойств JSON.

Таким образом, приведенный выше JSON может быть создан следующим образом:

// Allocate results using collection initializer syntax for the lists and for the dictionaries.
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/object-and-collection-initializers#collection-initializers
// https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-initialize-a-dictionary-with-a-collection-initializer
var results = new List<Dictionary<string, Dictionary<string, JsonParametersData>>>()
{
    new Dictionary<string, Dictionary<string, JsonParametersData>>()
    {
        {
            "testmodule1",
            new Dictionary<string, JsonParametersData>()
            {
                {
                    "name",
                    new JsonParametersData
                    {
                        required = true,
                        options = new List<string>() { "option1", "option2" },
                    }
                },
                {
                    "admin",
                    new JsonParametersData
                    {
                        required = true,
                        options = new List<string>() { "option1", "option2" },
                    }
                },
                {
                    "path",
                    new JsonParametersData
                    {
                        required = true,
                        options = new List<string>() { "option1", "option2" },
                    }
                }
            }
        },
    }
};

var moduleName = "testmodule2";
var moduleParameters = new [] { "name", "server", "port" };         

// Now add another result, allocating the dictionary with collection initializer syntax also
results.Add(new Dictionary<string, Dictionary<string, JsonParametersData>>()
    {
        {
            moduleName,
            // Loop through the parameters and convert them to a dictionary,
            // where the parameter name is the key and the corresponding JsonParametersData is the value
            moduleParameters
                .ToDictionary(n => n,
                              n => new JsonParametersData
                              {
                                  required = true, 
                                  options = new List<string>() { "option1", "option2" },
                              })
        }
    });

var json = JsonConvert.SerializeObject(results, Formatting.Indented);

Примечания:

Рабочий образец. Net fiddle здесь .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...