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
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.
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);
}
In C# convert Json string to Json Object
You can remodel your POCO:
public class ProductEntity
{
[JsonProperty("products")]
public List<Product> Products { get; set; }
}
public class Product
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("price")]
public string PricePerUnit { get; set; }
}
And then de-serialize it as follows:
internal class Solution1
{
static void Main(string[] args)
{
string str = @"
{
'products': [
{
'id': '1',
'name': 'red apple',
'price': '1.53'
},
{
'id': '2',
'name': 'green walnut',
'price': '0.25'
},
{
'id': '3',
'name': 'avocado',
'price': '0.33'
}
]
}";
ProductEntity result = JsonConvert.DeserializeObject<ProductEntity>(str);
}
}
What is best way to convert json string into array of objects?
I recommend to install Newtonsoft.Json via the NuGet package manager. Then decorate the members of the POCO class with the JsonProperty
attribute to tell the serializer which property matches to a specific JSON key:
public class MyJsonObject
{
[JsonProperty("Value")]
string Value { get; set; }
[JsonProperty("Name")]
string Name { get; set; }
}
You can the deserialize the JSON to a corresponding object instance:
var jsonString = "[{\"Value\": \"1\", \"Name\": \"One\"}, {\"Value\": \"2\", \"Name\": \"Two\"}]";
List<MyJsonObject> myJsonObjects = JsonConvert.DeserializeObject<List<MyJsonObject>>(jsonString);
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);
}
Cannot convert JSON string to List of object
This is because you need a container class at the top that has this list of orders as a property inside of it:
public class MyData
{
public List<FoodItem> Orders { get; set; }
{
var data = JsonConvert.DeserializeObject<MyData>(strProductsInCart);
var items = data.Orders;
Also, make sure you have public properties that match the name in the JSON. They can be Pascal case, too.
convert jsonstring to objects c#
Your string is not valid JSON, so making it valid JSON is the first step to process it quickly. The easiest thing to do is to make it a JSON array:
string jsonArray = "["
+ string.Join(", ", json.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
+ "]";
From then on it is straightforward (see my related answer: Easiest way to parse JSON response):
var result = JsonConvert.DeserializeObject<User[]>(jsonArray);
Another option is to split the lines yourself, and parse and add the items to a list manually.
Related Topics
Deserializing Json Data to C# Using Json.Net
How to Replace Multiple Spaces With a Single Space in C#
How to Cast Object of Type 'System.Dbnull' to Type 'System.String'
Get the Correct Week Number of a Given Date
How to Monitor Clipboard Changes in C#
How to Dynamically Create Generic C# Object Using Reflection
Why Can't I Define a Default Constructor For a Struct in .Net
Validating an Xml Against Referenced Xsd in C#
How to Retrieve Id of Inserted Entity Using Entity Framework
Why Doesn't C# Allow Static Methods to Implement an Interface
Finding Holes in 2D Point Sets
How to Get Children of a Wpf Container by Type
How to Build Splash Screen in Windows Forms Application