How to Convert JSON Text into Objects Using C#

Convert JSON String To C# Object

It looks like you're trying to deserialize to a raw object. You could create a Class that represents the object that you're converting to. This would be most useful in cases where you're dealing with larger objects or JSON Strings.

For instance:

  class Test {

String test;

String getTest() { return test; }
void setTest(String test) { this.test = test; }

}

Then your deserialization code would be:

   JavaScriptSerializer json_serializer = new JavaScriptSerializer();
Test routes_list =
(Test)json_serializer.DeserializeObject("{ \"test\":\"some data\" }");

More information can be found in this tutorial:
http://www.codeproject.com/Tips/79435/Deserialize-JSON-with-Csharp.aspx

How to convert JSON text into objects using C#

I recommend you to use JSON.NET. it is an open source library to serialize and deserialize your c# objects into json and Json objects into .net objects ...

Serialization Example:

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string json = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "Expiry": new Date(1230422400000),
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(json);

Performance Comparison To Other JSON serializiation Techniques
Sample Image

Convert JSON String to JSON Object c#

JObject defines method Parse for this:

JObject json = JObject.Parse(str);

You might want to refer to Json.NET documentation.

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 Convert JSON object to Custom C# object?

A good way to use JSON in C# is with JSON.NET

Quick Starts & API Documentation from JSON.NET - Official site help you work with it.

An example of how to use it:

public class User
{
public User(string json)
{
JObject jObject = JObject.Parse(json);
JToken jUser = jObject["user"];
name = (string) jUser["name"];
teamname = (string) jUser["teamname"];
email = (string) jUser["email"];
players = jUser["players"].ToArray();
}

public string name { get; set; }
public string teamname { get; set; }
public string email { get; set; }
public Array players { get; set; }
}

// Use
private void Run()
{
string json = @"{""user"":{""name"":""asdf"",""teamname"":""b"",""email"":""c"",""players"":[""1"",""2""]}}";
User user = new User(json);

Console.WriteLine("Name : " + user.name);
Console.WriteLine("Teamname : " + user.teamname);
Console.WriteLine("Email : " + user.email);
Console.WriteLine("Players:");

foreach (var player in user.players)
Console.WriteLine(player);
}

convert json to c# object

Why you don' t change your property @ref to reference or something else? there are plenty another words, you don't need to use c# reserved

public class Student
{
public string id{get;set;}
[System.Text.Json.Serializer.JsonPropertyName("ref")]
public int reference {get;set;}
}

How to convert an embedded JSON string to a JSON Object in C#

If you know the json response, you can create a model class for it. On VS 2022 you can right click on editor and do paste special Edit --> Paste special --> Paste JSON as Classes. You should get something like below.

public class Model 
{
public object[] paymentId { get; set; }
public object[] paymentRequestId { get; set; }
public object[][][] paymentAmount { get; set; }
public object[] paymentStatus { get; set; }
public object[][][] result { get; set; }
}

After using that Model class in your code, your code should look like below

using System.Text.Json;

public Model InquiryPaymentAPI(string id)
{

string paymentInfo = PaymentInquiry.IPayment(id);
return JsonSerializer.Deserialize<Model>(paymentInfo);

}

How to Convert Json to Object in C#

Using NewtonSoft Json.NET library (https://www.newtonsoft.com/json), you can do as follows:

JObject result = JObject.Parse(jsonString);

But your Json string looks more like an array, so probably JArray.Parse is what you need to use instead. Documentation with examples here:

https://www.newtonsoft.com/json/help/html/ParseJsonArray.htm

If you want to parse the internal elements as objects, thhe accepted answer of this question should provide you enough hints:

C# Parsing JSON array of objects

C# - How convert json string to class

Your model should be similar to this (For invalid c# names, you can use JsonProperty attribute) :

public class Reported
{
[JsonProperty("$id")]
public string id { get; set; }
public int BlockerId { get; set; }
public string Title { get; set; }
public int Date { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
}

public class List
{
[JsonProperty("$id")]
public string id { get; set; }
public int UserId { get; set; }
public string UID { get; set; }
public string Title { get; set; }
public string Sender { get; set; }
public string Answer { get; set; }
public string Comment { get; set; }
public object ProductTitle { get; set; }
public int CommentId { get; set; }
public string Logo { get; set; }
public int Date { get; set; }
public int AnswerDate { get; set; }
public bool AnswerEdit { get; set; }
public bool CommentEdit { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
public int ThisCountReport { get; set; }
public List<Reported> Reported { get; set; }
public int Gem { get; set; }
}

public class Result
{
[JsonProperty("$id")]
public string id { get; set; }
public int dateTime { get; set; }
public List<List> list { get; set; }
}

public class RootObject
{
[JsonProperty("$id")]
public string id { get; set; }
public Result Result { get; set; }
public string StatusCode { get; set; }
public object Description { get; set; }
}

Now you can deserialize as

var result = JsonConvert.DeserializeObject<RootObject>(jsonstring);

BTW: http://json2csharp.com/ can help to guess your model when working with json.



Related Topics



Leave a reply



Submit