0

i have a HTTPclient and im sending request to a Server. The response from the server is a JSON. In this Json is also an array. I want do display the information from the JSON in the consol. I get all information from the JSON, but i dont get the array displayed in my console.

The JSON looks like this:

{
    "Name1": "Karl",
    "Name2": "Peter",
    "Name3": "Wilhelm",
    "PreNames": {
        "PreName": "Werner",
        "PreName2": "Josef"
    }
}

So now my Code so far:

public class PreNames //for Array
    {
        public string PreName { get; set; }
        public string PreName2{ get; set; }
    }

    public class Names//for JSON
    {
        public string Name1{ get; set; }
        public string Name2{ get; set; }
        public string Name3{ get; set; }
    }

And my Main:

if (Response().IsSuccessStatusCode)
        {
            var namesJ= Response().Content.ReadAsAsync<IEnumerable<Names>>().Result;
            var preNamesJ= await Response().Content.ReadAsAsync<List<PreNames>>();



            foreach (var a in namesJ)

            {

                Console.WriteLine("Name1: {0}", a.Name1);

                foreach(var b in preNamesJ)
                {
                    Console.WriteLine("{0}", b.PreName);
                }
                
            }

So in the console are all names displayed, but not the PreNames so i cant get the PreNames from the array in the JSON...

I Hope somebody could help me :)

6
  • 1
    add proper JSON this one seems not valid Commented Sep 22, 2020 at 12:48
  • how i do that ? :/ Commented Sep 22, 2020 at 12:49
  • 1
    I your Main async ? If not, you might want to remove the await keyword and add a .Result() at the end of the line. If it is, you should remove the .Result(), and add an await keyword at the right of the "=" Commented Sep 22, 2020 at 12:57
  • the Method for the JSON is normal, but the Method for the array is Async. also not worked Commented Sep 22, 2020 at 13:02
  • the comment on the async, .Result() looks correct the json, if that is exactly what you are getting back is invalid, its should be something like: { "Name1": "Karl", "Name2": "Peter", "Name3": "Wilhelm", "PreNames": [ { "PreName": "Werner" }, { "PreName2": "Josef" } ] } You cannot have a json object array without putting the key/value pairs in {...} Commented Sep 22, 2020 at 13:18

4 Answers 4

1

Add the PreNames property to your Names class and only read one time.

public class Names//for JSON
    {
        public string Name1{ get; set; }
        public string Name2{ get; set; }
        public string Name3{ get; set; }
        public List<PreNames> PreNames { get; set;}
    }

Once you read in the result one time, you can access the elements via the main object

var namesJ= Response().Content.ReadAsAsync<Names>().Result;
foreach(var names in namesJ.PreNames)
{
  Console.WriteLine(names.PreName);
}

updated Since you changed the json and made PreNames just an object instead of an array, simply access the property of related object.

public class Names//for JSON
    {
        public string Name1{ get; set; }
        public string Name2{ get; set; }
        public string Name3{ get; set; }
        public PreNames PreNames { get; set;}
    }

var namesJ= Response().Content.ReadAsAsync<Names>().Result;
Console.WriteLine(namesJ.PreNames.Name);
Sign up to request clarification or add additional context in comments.

Comments

0

@Leonc443, Here is a working code

    using Newtonsoft.Json;  //add this nuget package
    using System;

    namespace ConsoleApp
    {
        class Program
        {
            public static void Main(string[] args)
            {
                string json = @"{
                    'Name1': 'Karl',
                    'Name2': 'Peter',
                    'Name3': 'Wilhelm',
                    'PreNames': {
                                'PreName': 'Werner',
                                'PreName2': 'Josef'
                            }
                }";  // data received from api
                var names = JsonConvert.DeserializeObject<Names>(json);
                Console.WriteLine(names.Name1);     // Karl
                Console.WriteLine(names.Name2);     //Peter
                Console.WriteLine(names.Name3);     //Wilhelm
                Console.WriteLine(names.PreNames.PreName);      //Werner
                Console.WriteLine(names.PreNames.PreName2);     // Josef

            }
        }
        public class Names
        {
            public string Name1 { get; set; }
            public string Name2 { get; set; }
            public string Name3 { get; set; }
            public PreNames PreNames { get; set; }
        }

        public class PreNames
        {
            public string PreName { get; set; }
            public string PreName2 { get; set; }
        }
    }

Please let me know if this helps

Comments

0

In case your Json looks like:

{
    "Name1": "Karl",
    "Name2": "Peter",
    "Name3": "Wilhelm",
    "PreNames": {
        "PreName": "Werner",
        "PreName2": "Josef"
    }
}

If the PreNames are in the Names, you shuld add a PreNames field to the Names Class.

public class Names
{
    public string Name1 { get; set; }
    public string Name2 { get; set; }
    public string Name3 { get; set; }
    public PreNames PreNames { get; set; }
}

Then you can read the inner PreNames:

foreach (var b in a.Prenames) {
    Console.WriteLine(b.PreName);
}

But I'm not sure if I understand your question.

Comments

0

I don't have sufficient reputation to comment, so... I'll give it a try.

Edited after proper json updated in Answer.

  1. Change your class Names
public class Names
{
    public string Name1 { get; set; }
    public string Name2 { get; set; }
    public string Name3 { get; set; }
    public PreNames PreNames { get; set; }
}
  1. Then deserialize it with JsonConvert
var json = await Response().Content.ReadAsStringAsync();
var names = JsonConvert.DeserializeObject<Names>(json);
  1. Then access data
Console.WriteLine($"Name 1: {names.Name1}");
Console.WriteLine($"Prename 1: {names.PreNames.PreName}");

4 Comments

the "name.PreNames?.PreName" doesnt work... after PreName?, i am not able to choose the PreName
If you mouseover name from (var name in names) in debug mode, you should see Name1, Name2, Name3 and PreNames. I added the ? just in case the value (PreNames) is null which seems to be the case. Could you please clarify what exactly is that part of the original json you receive?
when i mouseover, i can see that in "json" is the whole response, but "name" is null. and the ? is also added
Just saw you edited the first json, so here it is (I will update my answer too): dotnetfiddle.net/9EG8WK

Your Answer

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