-1
String Contents =
{
    "links":[
    {
        ".tag":"file",
        "url":"myURL",
        "id":"CCCCC",
        "name":"CCCC",
        "path_lower":"CCCC"
    },
    {
        "url".. and so on.
    }

    JObject json = JObject.Parse(contents);
    Console.WriteLine(json.GetValue("links.url"));

I am trying to get all the URL values and store them into an array. The problem is that this code does not parse anything.

The main json is links and the rest is under it. How can I go about getting all the URL values?

Andrew Halil
  • 1,195
  • 15
  • 15
  • 21
Csaas3311
  • 13
  • 5

1 Answers1

0
  1. Take json["links"] as JArray.
  2. Use Linq to retrieve url from the element in (1) and cast it to string.
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json.Linq;

JObject json = JObject.Parse(contents);
JArray array = json["links"] as JArray;

List<string> links = array.Select(x => (string)x["url"]).ToList();

Sample demo on .NET Fiddle

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
  • You my sir are the best!!! This worked perfect. One quick question. Why was JArray needed? – Csaas3311 Dec 26 '21 at 05:14
  • Hi, you're welcome. Because `links` is an array. You have to cast as `JArray` before retrieving each element in the array. And wish you enjoy the festive season. – Yong Shun Dec 26 '21 at 05:16
  • Sounds great! Two more questions. 1. How efficient is this method? 2. How do I know if a JSON is an array? – Csaas3311 Dec 26 '21 at 05:22
  • Sorry for the late reply. 1. For efficiency, it depends on how is your JSON object. Whether is your JSON object is dynamic or not, the size. This article [JObject.Parse vs JsonConvert.DeserializeObject](https://stackoverflow.com/questions/23645034/jobject-parse-vs-jsonconvert-deserializeobject) may be useful for you. 2. when the object/property has the [value surrounded with `[]`](https://restfulapi.net/json-array/). – Yong Shun Dec 26 '21 at 05:56
  • So another issue. This code sometimes does not work when it is a single JSOn and not an array. How can I check to see if its an Array or not easily? ALso how would I parse that single JSOn? – Csaas3311 Dec 26 '21 at 07:58
  • Bascially I need to see if the data contains Links or not. If it contains links its an array, if it does not contain links its a single object. if (json.ContainsKey("links")) would this work? – Csaas3311 Dec 26 '21 at 08:11
  • This [demo](https://dotnetfiddle.net/XMf4Tu) may meet your requirement. – Yong Shun Dec 26 '21 at 10:52
  • This concept is nice, but for the JSOn object that is not an array, it does not start with links or anything. It justs all the values listed. So would it be all this: JObject jLink = json as JObject; Then var link = (string)jLink["url"]; – Csaas3311 Dec 26 '21 at 21:05