How to read and iterate JSON file contents?

自闭症网瘾萝莉.ら 提交于 2020-01-25 12:49:05

问题


This is my JSON file.

{
  "webroot": "wwwroot",
  "version": "1.0.0-*",

  "dependencies": {
    "EntityFramework.SqlServer": "7.0.0-beta5",
    "EntityFramework.Commands": "7.0.0-beta5",
    "Microsoft.AspNet.Mvc": "6.0.0-beta5",
  },

  "exclude": [
    "wwwroot",
    "node_modules",
    "bower_components"
  ],
}

I can read value of "webroot" as string and "exclude" as array using following snippet.

string file = File.ReadAllText("project.json");
Product pro = JsonConvert.DeserializeObject<Product>(file);

But I cannot read the value of dependencies. Its throwing exception as "Error reading string. Unexpected token: StartObject. Path 'dependencies',..."

My requirement is to read each value under dependency node and validate it. Then to add a new value and write it back to the json fie. Please help.

Edit: My product class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Product
    {
        private string webroot;
        private string[] exclude;
        private string[] dependencies;
        public string WebRoot
        {
            get
            {
                return webroot;
            }
            set
            {
                webroot = value;
            }
        }

        public string[] Exclude
        {
            get
            {
                return exclude;
            }
            set
            {
                exclude = value;
            }
        }

        public string[] Dependencies
        {
            get
            {
                return dependencies;
            }
            set
            {
                dependencies = value;
            }
        }
    }
}

Its throwing exception:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.String[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.


回答1:


Dependencies property is object with dynamic properties so you need some kind of dynamic object in your C# class.

The problem can be solved by using Dictionary<string, string> for Dependencies property. Here is an example:

public class Product
{
    public string Webroot { get; set; }
    public string Version { get; set; }
    public Dictionary<string, string> Dependencies { get; set; }
    public string[] Exclude { get; set; }
}

[ ... ]

static void Main()
{
    string json = File.ReadAllText("project.json");
    Product pro = JsonConvert.DeserializeObject<Product>(json);

    foreach (var dependency in pro.Dependencies)
    {
        // Here you can validate each property instead of printing it ...
        Console.WriteLine("{0}: {1}", dependency.Key, dependency.Value);
    }

    pro.Dependencies.Add("NewProperty", "NewValue");

    var resultJson = JsonConvert.SerializeObject(pro, Formatting.Indented);
    Console.WriteLine(resultJson);
}



回答2:


To deserialize the file properly, your classes should look like this. Notice the JsonProperty attributes from Json.NET.

using Newtonsoft.Json;

public class Product
{
    public string webroot { get; set; }
    public string version { get; set; }
    public Dependencies dependencies { get; set; }
    public string[] exclude { get; set; }
}

public class Dependencies
{
    [JsonProperty("EntityFramework.SqlServer")]
    public string EntityFrameworkSqlServer { get; set; }
    [JsonProperty("EntityFramework.Commands")]
    public string EntityFrameworkCommands { get; set; }
    [JsonProperty("Microsoft.AspNet.Mvc")]
    public string MicrosoftAspNetMvc { get; set; }
}

Then you can directly deserialize it using Json.NET like this

string content = File.ReadAllText(@"C:\YourDirectory\product.json");
var product = JsonConvert.DeserializeObject<Product>(content);

In case, you just want to read some property/part of the json, you can use Linq-to-Json like this

string content = File.ReadAllText(@"C:\YourDirectory\product.json");

JObject jObj = JObject.Parse(content);
string entityFrameworkSqlServer = (string)jObj["dependencies"]["EntityFramework.SqlServer"];


来源:https://stackoverflow.com/questions/33119297/how-to-read-and-iterate-json-file-contents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!