How to Parse Json List or Object in C#

Convert Json String to C# Object List

You can use json2csharp.com to Convert your json to object model

  • Go to json2csharp.com
  • Past your JSON in the Box.
  • Clik on Generate.
  • You will get C# Code for your object model
  • Deserialize by var model = JsonConvert.DeserializeObject<RootObject>(json); using NewtonJson

Here, It will generate something like this:

public class MatrixModel
{
public class Option
{
public string text { get; set; }
public string selectedMarks { get; set; }
}

public class Model
{
public List<Option> options { get; set; }
public int maxOptions { get; set; }
public int minOptions { get; set; }
public bool isAnswerRequired { get; set; }
public string selectedOption { get; set; }
public string answerText { get; set; }
public bool isRangeType { get; set; }
public string from { get; set; }
public string to { get; set; }
public string mins { get; set; }
public string secs { get; set; }
}

public class Question
{
public int QuestionId { get; set; }
public string QuestionText { get; set; }
public int TypeId { get; set; }
public string TypeName { get; set; }
public Model Model { get; set; }
}

public class RootObject
{
public Question Question { get; set; }
public string CheckType { get; set; }
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
public string S4 { get; set; }
public string S5 { get; set; }
public string S6 { get; set; }
public string S7 { get; set; }
public string S8 { get; set; }
public string S9 { get; set; }
public string S10 { get; set; }
public string ScoreIfNoMatch { get; set; }
}
}

Then you can deserialize as:

var model = JsonConvert.DeserializeObject<List<MatrixModel.RootObject>>(json);

How to parse JSON list or object in C#

If your objects are not fixed and data must be configurable then Newtonsoft.json has one feature that to be use here and that is [JsonExtensionData]. Read more

Extension data is now written when an object is serialized. Reading and writing extension data makes it possible to automatically round-trip all JSON without adding every property to the .NET type you’re deserializing to. Only declare the properties you’re interested in and let extension data do the rest.

So in your case your Response class will be

public class Response
{
public string statusCode { get; set; }
public string status { get; set; }

[JsonExtensionData]
public Dictionary<string, JToken> data;
}

All your data in data key will be collected in [JsonExtensionData] property.

You need to perform operations on [JsonExtensionData] property to get your key/value pair. like

public class Employee
{
public string empId { get; set; }
public string empName { get; set; }
public int empCode { get; set; }
}

And you can perform opration like

var json = "Your response";

JObject jObject = JObject.Parse(json);

var statusCode = jObject["statusCode"];

var status = jObject["status"];

var data = jObject["data"];

if (data.Type == JTokenType.Array)
{
var arrayData = data.ToObject<List<Employee>>();
}
else
if (data.Type == JTokenType.Object)
{
var objData = data.ToObject<Employee>();
}

How to parse JSON object into a list of objects in C#

Copy an example JSON response to your clipboard and generate some Json classes either by:

a. In Visual Studio select Edit / Paste Special / Paste JSON As Classes

b. If your data is not sensitive / you can clean it, use an online site such as http://json2csharp.com

Then deserialize from the Root object.

using var stream = new MemoryStream(data);
using var reader = new StreamReader(stream, Encoding.UTF8);
using var jsonReader = new JsonTextReader(reader);

var json = JsonSerializer.Create().Deserialize<Rootobject>(jsonReader);

Then take the bit you need.

var response = json.hits.hits;

You can further optimise the process by scrubbing all properties on the outer objects that you don't want to deserialize into.

how to parse json list at c#

On json2csharp.com you can generate classes for your JSON, for your JSON they can look like:

public class Adjustment
{
public string CardNumber { get; set; }
public string TimeStamp { get; set; }
public double Point { get; set; }
}

public class RootObject
{
public int Id { get; set; }
public Adjustment Adjustment { get; set; }
}

And then deserialise it:

List<RootObject> o = JsonConvert.DeserializeObject<List<RootObject>>(string json)

How to parse JSON which include list of objects

I would use the first variant. Your solution is not working because the json has different names than your class. You should rename:

public List<Picture> Pictures { get; set; }

to

public List<Picture> hits { get; set; }

I am not sure if JsonConvert would work with Hits, but if it does you should use it due to naming conventions.

EDIT: If you want to keep using Pictures as a property name you can use the JsonProperty attribute, like this:

[JsonProperty("hits")]
public List<Picture> Pictures { get; set; }

Parsing JSON with LINQ into List of Objects

Use This as your Model

using System;
using System.Collections.Generic;

using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

public partial class JsonModel
{
[JsonProperty("featured")]
public Featured Featured { get; set; }

[JsonProperty("categories")]
public List<Category> Categories { get; set; }
}

public partial class Category
{
[JsonProperty("id")]
public long Id { get; set; }

[JsonProperty("title")]
public string Title { get; set; }

[JsonProperty("description")]
public object Description { get; set; }

[JsonProperty("position")]
public long Position { get; set; }

[JsonProperty("media")]
public List<Featured> Media { get; set; }
}

public partial class Featured
{
[JsonProperty("id")]
public long Id { get; set; }

[JsonProperty("title")]
public string Title { get; set; }

[JsonProperty("description")]
public string Description { get; set; }

[JsonProperty("short_description")]
public string ShortDescription { get; set; }

[JsonProperty("rating_avg")]
public long RatingAvg { get; set; }

[JsonProperty("image")]
public string Image { get; set; }

[JsonProperty("category_media", NullValueHandling = NullValueHandling.Ignore)]
public CategoryMedia CategoryMedia { get; set; }
}

public partial class CategoryMedia
{
[JsonProperty("position")]
public long Position { get; set; }

[JsonProperty("category_id")]
public long CategoryId { get; set; }

[JsonProperty("media_id")]
public long MediaId { get; set; }

[JsonProperty("id")]
public long Id { get; set; }
}
}

Then do this in your Class:

var info = JsonConvert.DeserializeObject<JsonModel>(json);
var featured = info.Featured;
var categories = info.Categories;

Parsing json to list of objects and displaying data in console

That to string call looks incorrect. You need to construct a string using the properties of the object in the collection.

For example

currencies.ForEach(c => 
Console.WriteLine($"drzava_iso: {c.Drzava_iso}, Sifra_valute: {c.Sifra_valute}, ...")
);

Everything else looks as it should.

How to parse a list of the same object to JSON in different name

You have to use a Dictionary<string, Person> when I am not that wrong.
This should serialize it that way, you want it.

You can add the Attribute [JsonIgnore] to Name optionally, if you don't want redundant data.

Edit: You can serialize a list directly to a dictionary by using a custom JsonConverter: Newtonsoft.Json serialize collection (with indexer) as dictionary



Related Topics



Leave a reply



Submit