Adin
Adin

Reputation: 11

How to deserialize JSON string and parse it properly in C#?

This question is asked many times but the answers do not fit my needs. I have a sample JSON string which is an JSON array. I want to parse it and be able to choose what values to print

In my first class I download the JSON into string and parse it using jsonConvert.DeserializeObject

   using Newtonsoft.Json;

   namespace JSON_parser_2
   {
class Program
{
    static void Main(string[] args)
    {
        WebClient client = new WebClient();
        string downloadedString =     client.DownloadString("https://jsonplaceholder.typicode.com/posts");
        var result = JsonConvert.DeserializeObject<jsonStorage>(downloadedString);

The "JsonStorage" is the class in which I defined the following

    public string userId { get; set; }
    public string id { get; set; }
    public string title { get; set; }
    public string body { get; set; }

Now, In my first class I want to print this whole parsed JSON or only title or body, how can I do it? Ultimately, I want to print all sample comments from a given link.

Upvotes: 0

Views: 374

Answers (2)

kurakura88
kurakura88

Reputation: 2305

public class jsonStorage
{
    // your properties here
    ...
    ...
    // override the ToString
    public override string ToString()
    {
        return "userid=" + userId + Environment.NewLine +
               "id=" + id + Environment.NewLine +
               "title=" + title + Environment.NewLine +
               "body=" + body;
    }
}

In the main, after deserializing, do ToString()

var result = JsonConvert.DeserializeObject<jsonStorage>(downloadedString);
Console.WriteLine(result.ToString());

Upvotes: 0

Matt McKinney
Matt McKinney

Reputation: 81

One way to do this is to use the Flurl.Http library to retrieve the json a a list of strongly typed JsonStorage objects. By casting it into a list of strongly tped objects, you can then control which properties are printed. Just download the Flurl.Http nuget package and then you can use the following code:

using System;
using System.Collections.Generic;
using Flurl.Http;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var httpResponse = "https://jsonplaceholder.typicode.com/posts"
                            .GetJsonAsync<List<JsonStorage>>();

            httpResponse.Wait();

            var results = httpResponse.Result;

            foreach(var result in results)
            {
                Console.WriteLine($"title: {result.title}, body: {result.body}");
            }

            Console.ReadLine();
         }    
    }

    class JsonStorage
    {
        public string userId { get; set; }
        public string id { get; set; }
        public string title { get; set; }
        public string body { get; set; }
    }
}

Upvotes: 1

Related Questions