0

I'm call an API that returns the following json

{
  "services":{
     "Home":{
        "Homecall":{
           "id":"10"
        },
        "Two Day":{
           "id":"11"
        },
        "Three Day":{
           "id":"12"
        }
     }
  }
}

What would be the best possible way to parse this so it returns 'Home' as a unqiue variable, "homecall","Two day" and "three day" along with their ID in c#?

7
  • 2
    There are no arrays in this JSON string. Home is a dictionary/object with attributes named HomeCall, Two Day, Three Day. You can deserialize it to Dictionary<string,Whatever> Commented Jan 20, 2023 at 15:31
  • The api isn't returning any array in the JSON string, this is what has stumped me Commented Jan 20, 2023 at 15:32
  • 2
    Use Dictionary<string,Whatever> as Home's type. Unless you want even services to be a dictionary. What does this JSON document contain? And what do you want to do with its contents? Commented Jan 20, 2023 at 15:33
  • You are the developer of the mentioned API and can change the implementation so you actually get an array? Commented Jan 20, 2023 at 15:42
  • Panagiotis, once im able to get this keys they'll be passed into a sql. I'll give your dictionary method a go. Commented Jan 20, 2023 at 15:43

1 Answer 1

2

you can try something like this

HomeClass home = new HomeClass
{
    Home = ((JObject)JObject.Parse(json)["services"]["Home"]).Properties()
        .Select(h => new MyClass { Name = h.Name, Id = Convert.ToInt64(h.Value["id"]) })
        .ToList()
};

public class HomeClass
{
    public List<MyClass> Home { get; set; }
}
public class MyClass
{
    public long Id { get; set; }
    public string Name { get; set; }
}

output in a json format

{
  "Home": [
    {
      "Id": 10,
      "Name": "Homecall"
    },
    {
      "Id": 11,
      "Name": "Two Day"
    },
    {
      "Id": 12,
      "Name": "Three Day"
    }
  ]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.