0

I have the following json:

{
  "key445" : {
    "text" : "cat",
    "id" : 445
  },
  "key457" : {
    "text" : "mouse",
    "id" : 457
  },
  "key458" : {
    "text" : "rodent",
    "id" : 458
  }
}

I am trying extract text and id into a List<TextIdentifier> (a class with string and an int), or even separately into List<string> and List<int>.

I read the text into JObject using JObject.Parse method. However, I can't figure out how to get to the text and id nodes. I've tried the following but it returns nothing.

var textTokens = o.SelectTokens("/*/text");
var idTokens = o.SelectTokens("/*/id");

How can I get to the tokens I want?

5
  • 1
    Any reason for parsing into a JObject rather than parsing into Dictionary<string, TextIdentifier> which I suspect would just work immediately?
    – Jon Skeet
    Dec 10, 2020 at 18:51
  • @JonSkeet No reason, I just don't know how to do it. JObject seemed like a good way to debug this. Dec 10, 2020 at 18:55
  • 1
    Right. So if TextIdentifier has writable properties for Text and Id, that's all you need to do :)
    – Jon Skeet
    Dec 10, 2020 at 18:57
  • @JonSkeet My issue is finding the right JsonPath query to extract these tokens from json. Once I get them, I could definitely write them to an object. Dec 10, 2020 at 19:01
  • 1
    My point is that you don't need to use JsonPath at all. Just convert the whole of your object to a Dictionary<string, TextIdentifier> and then if you only need the values, just use the Values property. Unless you need them in the order of the JSON file, which would be quite fragile. (Adding a sample now.)
    – Jon Skeet
    Dec 10, 2020 at 19:05

1 Answer 1

2

I would just convert the whole JSON into a Dictionary<string, TextIdentifier> instead of trying to use JsonPath at all:

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

public class TextIdentifier
{
    public string Text { get; set; }
    public int Id { get; set; }
    public override string ToString() => $"Id: {Id}; Text: {Text}";
}

public class Test
{
    static void Main()
    {
        var json = File.ReadAllText("test.json");
        var dictionary = JsonConvert.DeserializeObject<Dictionary<string, TextIdentifier>>(json);

        foreach (var pair in dictionary)
        {
            Console.WriteLine($"{pair.Key} => {pair.Value}");
        }
    }
}

Output:

key445 => Id: 445; Text: cat
key457 => Id: 457; Text: mouse
key458 => Id: 458; Text: rodent

If you don't care about the keys, you can use dictionary.Values.ToList() to get a List<TextIdentifier> although you shouldn't rely on the order of them.

1
  • Wow, that is actually perfect. I wish I could upvote more. Dec 10, 2020 at 19:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.