简体   繁体   中英

Extracting a node from Json File in C#

In the JSON File, I would like to extract the data from the node. Say like I wanted to extract the book node or value which is within goods node. Here is my JSON file.

JSON

    {  
   "store":[  
      {  
         "name":"Sunshine Department Store",
         "address":"Wangfujing Street",
         "goods":{  
            "book":[  
               {  
                  "category":"Reference",
                  "title":"Sayings of the Century",
                  "author":"Nigel Rees",
                  "price":8.88
               },
               {  
                  "category":"Fiction",
                  "title":"Sword of Honour",
                  "author":"Evelyn Waugh",
                  "price":12.66
               }
            ],
            "bicycle":{  
               "type":"GIANT OCR2600",
               "color":"White",
               "price":276
            }
         }
      }
   ]
}

Code

private string ParseBookNode(JObject bookJSONFile)
{
    JArray bookJson = null;
    string bookFarmNode = null;
    if (bookJSONFile != null && bookJSONFile["store"] != null)
    {
        bookJson = (JArray)bookJSONFile["store"];
        bookFarmNode = bookJson[0].ToString();

        if (bookJSONFile["book"] != null)
        {
            bookJson = (JArray)bookJSONFile["book"];
            bookFarmNode = bookJson[0].ToString();
        }
    }
    else
    {
        throw new Exception("Book node not found.");
    }
    return bookFarmNode;
}

How can I extract data along these lines??

if (bookJSONFile["book"] != null)
{
    bookJson = (JArray)bookJSONFile["book"];
    bookFarmNode = bookJson[0].ToString();
}

Your code bears little relation to your data structure, and your variable names are confusing, which probably isn't helping you organise the code properly.

This (untested I'm afraid) should get you as far as accessing the book array (in the first object of the "store" array), I think.

private string ParseBookNode(JObject bookJSONFile)
{
    JArray storeList = null;
    JObject store = null;
    JObject goods = null;
    JArray bookList = null;

    if (bookJSONFile != null && bookJSONFile["store"] != null)
    {
        storeList = (JArray)bookJSONFile["store"];
        store = bookJson[0];
        goods = store["goods"];

        if (goods["book"] != null)
        {
            bookList = (JArray)goods["book"];
        }
    }
    else
    {
        throw new Exception("File is empty, or Store node not found.");
    }
    return "something, not sure what you want to return here";
}

Apologies for any mistakes, but hopefully you get the general idea. https://www.newtonsoft.com/json/help/html/Introduction.htm has comprehensive documentation as well on how to use JArray and JObject.

You can access this with Json.Net.

I just added look up by category just to show you that you can do things like this.

    public static JObject GetBook(JObject jObject, string category)
    {
        JObject returnValue = null;
        try
        {
            var array = jObject.Property("store").Value;
            var first = (JObject)array.FirstOrDefault();

            var goods = first?.Property("goods").Value;

            var books = ((JObject)goods).Property("book").Value;

            var booksArray = books as JArray;

            foreach (JObject book in booksArray)
            {
                if (book.Property("category")?.Value?.ToString() == category)
                {
                    returnValue = book;
                    break;
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            throw;
        }

        return returnValue;
    }

You can try Cinchoo ETL - an open source library to parsing / writing JSON files. Here is how you can parse and load book nodes

using (var jr = new ChoJSONReader("sample9.json").WithJSONPath("$..book")
    )
{
    foreach (var x in jr)
    {
        Console.WriteLine($"Category: {x.category}");
        Console.WriteLine($"Title: {x.title}");
        Console.WriteLine($"Author: {x.author}");
        Console.WriteLine($"Price: {x.price}");
    }
}

If you have POCO book type defined as below

public class Book
{
    public string Category { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
    public double Price { get; set; }
}

You can load them as below

using (var jr = new ChoJSONReader<Book>("sample9.json").WithJSONPath("$..book")
)
{
    foreach (var x in jr)
    {
        Console.WriteLine($"Category: {x.Category}");
        Console.WriteLine($"Title: {x.Title}");
        Console.WriteLine($"Author: {x.Author}");
        Console.WriteLine($"Price: {x.Price}");
    }
}

Hope this helps.

Disclaimer: I'm the author of the library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM