I can't seem to be bale to convert Json to my desired List class.
I got the Json file and passed it to Json to C#
and it generated the class:
public class Customers
{
[JsonProperty("Customers")]
public string Oid { get; set; }
[JsonProperty("Customers")]
public string Name { get; set; }
[JsonProperty("Customers")]
public string Title { get; set; }
[JsonProperty("Customers")]
public string Kwdikos { get; set; }
[JsonProperty("Customers")]
public string AFM { get; set; }
[JsonProperty("Customers")]
public string Email { get; set; }
[JsonProperty("Customers")]
public string DOY { get; set; }
[JsonProperty("Customers")]
public string Occupation { get; set; }
[JsonProperty("Customers")]
public int FPA { get; set; }
}
public class CustomersList
{
[JsonProperty("Customers")]
public List<Customers> _customersList { get; set; }
}
and I am using the code to get the Json to my List Class like this:
var content = await response.Content.ReadAsStringAsync();
var customers = JsonConvert.DeserializeObject<List<CustomersList>>(content, new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
But I get an error saying:
Newtonsoft.Json.JsonSerliazitaionException : 'Error converting value
"(My Json file)" to type
'System.Collections.Generic.List`1[DemoProject6.CustomersList]'. Path
'', line 1, position 37574.'
Any Idea on how to solve this? Thank you for your time !!!
JsonPropertyAttribute specified for the property, the name in JSON texte. But in your example, all properties have [JsonProperty("Customers")]. The JSON generated by your model will be :
{
"Customer": [{
"Customers": "Oid value",
"Customers": "Name value",
"Customers": "Title value",
...
}]
}
In JSON, you can't have by level some property with the same name.
By default, the json property's name is class property's name.
Solution :
public class Customers
{
public string Oid { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public string Kwdikos { get; set; }
public string AFM { get; set; }
public string Email { get; set; }
public string DOY { get; set; }
public string Occupation { get; set; }
public int FPA { get; set; }
}
Then
var content = await response.Content.ReadAsStringAsync();
var customers = JsonConvert.DeserializeObject<List<Customers>>(content);
edit:
I think the response's content isn't well formatted.
Maybe you can try :
var content = await response.Content.ReadAsStringAsync();
var customersJson = Regex.Unescape(content.Substring(1, content.Length - 2));
var customers = JsonConvert.DeserializeObject<List<Customers>>(customersJson);
Related
I'm using a API that give me this json as a response,
This is json response body :
{
"meta":{
"status":200,
"message":"success"
},
"data":{
"0":{
"MsgID":"2661689817",
"Status":"6",
"SendTime":"2021-10-3114:30:04",
"DeliverTime":"2021-10-31 14:30:07"
}
}
}
My problem is "0":{... in this body.
How can I deserialize this into a Class.
it can't deserialize on "string _0" prop.
As the #TheGeneral says, this is like a dictionary. You can parse - like this:
public void ParseObject()
{
var response = #"{
'meta':{
'status':200,
'message':'success'
},
'data':{
'0':{
'MsgID':'2661689817',
'Status':'6',
'SendTime':'2021-10-3114:30:04',
'DeliverTime':'2021-10-31 14:30:07'
}
}
}";
var responseObj = JsonConvert.DeserializeObject<MetaData>(response);
}
public class MetaData
{
public Meta Meta { get; set; }
public Dictionary<int, Data> Data { get; set; }
}
public class Meta
{
public string Status { get; set; }
public string Message { get; set; }
}
public class Data
{
public string MsgId { get; set; }
public string Status { get; set; }
public string SendTime { get; set; }
}
try using JsonProperty
public class Data
{
[JsonProperty("0") ]
public _0 _0 { get; set; }
}
public class _0
{
public string MsgID { get; set; }
public string Status { get; set; }
public string SendTime { get; set; }
public string DeliverTime { get; set; }
}
hello i've got some problems in c#(xamarin)
i followed XXX tutorials about pharsing..
I only need the Value.
Can someone tell me how i solve that problem?
my Json:
{
"Header":{
"Version":5,
"Device":"80",
"Timestamp":1610066048
},
"Data":{
"Inputs":[
{
"Number":2,
"AD":"A",
"Value":{
"Value":62.0,
"Unit":"1"
}
}
]
},
"Status":"OK",
"Status code":0
}
C#
var client = new WebClient();
string json = client.DownloadString("https://XXXXXXX.com/heizung.php");
Value1 news = JsonConvert.DeserializeObject<Value1>(json);
Ausgabe.Text = news.Value;
My Class
public class Header
{
public int Version { get; set; }
public string Device { get; set; }
public int Timestamp { get; set; }
}
public class Value1
{
public string Value { get; set; }
public string Unit { get; set; }
}
public class Input
{
public int Number { get; set; }
public string AD { get; set; }
public Value1 Value { get; set; }
}
public class Data
{
public List<Input> Inputs { get; set; }
}
public class Root
{
public Header Header { get; set; }
public Data Data { get; set; }
public string Status { get; set; }
public int Statuscode { get; set; }
}
Thanks, i hope y'all have a nice day.
Deserialize Root object and track value down:
Root news = JsonConvert.DeserializeObject<Root>(json);
Ausgabe.Text = news.Data.Inputs[0].Value.Value;
You should deserialize your json as a Root class:
var root = JsonConvert.DeserializeObject<Root>(json);
After the root object is deserialized you can select whatever value you need. E.g.:
var values = root.Data.Inputs.Select(i => i.Value.Value); // string sequence
I am new to C#
Following is the JSON string I am getting from the web API.
I am trying to store the JSON string into a class and then store the JSON string into an SQL table.
But the C# code is failing to deserialize JSON into class. And the message box returns the null exception error.
JSON
{
"Count":3,
"data":[
{
"Cost1":{
"amount":111,
"currencyCode":"ABC"
},
"Cost2":{
"amount":22.2,
"currencyCode":"XYZ"
},
"Id":"007"
},
{
"Cost1":{
"amount":555,
"currencyCode":"ABC"
},
"Cost2":{
"amount":444,
"currencyCode":"XYZ"
},
"Id":"008"
},
{
"Cost1":{
"amount":666,
"currencyCode":"ABC"
},
"Cost2":{
"amount":8882,
"currencyCode":"XYZ"
},
"Id":"009"
}
],
"pending":[
],
"#up":"Test Data"
}
C# Code
public class ParceJSN {
public int Count {
get;
set;
}
public string data {
get;
set;
}
public string pending {
get;
set;
}
public string up {
get;
set;
}
}
public void Main() {
Task < string > task = MakeRequest(db_token); //Returns the JSON string
var fr = task.Result;
ParceJSN rst = JsonConvert.DeserializeObject < ParceJSN > (fr.ToString());
MessageBox.Show(rst.TotalCount.ToString());
Dts.TaskResult = (int) ScriptResults.Success;
}
Your C# model is incorrect. Here's a really handy tool that I use when I need to generate C# classes based on some JSON - json2csharp.com
The correct class is:
public class Cost1 {
public int amount { get; set; }
public string currencyCode { get; set; }
}
public class Cost2 {
public double amount { get; set; }
public string currencyCode { get; set; }
}
public class Datum {
public Cost1 Cost1 { get; set; }
public Cost2 Cost2 { get; set; }
public string Id { get; set; }
}
public class Root {
public int Count { get; set; }
public List<Datum> data { get; set; }
public List<object> pending { get; set; }
[JsonProperty("#up")]
public string Up { get; set; }
}
Now that you have the correct model, you can now do the following to deserialize your JSON string into a Root object which is defined above:
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(YOUR_JSON_STRING);
I am having a difficulty trying to extract data from the following JSON table:
[
{"type":"header","version":"4.8.3","comment":"Export to JSON plugin for PHPMyAdmin"},
{"type":"database","name":"archaism_dictionary"},
{"type":"table","name":"dictionary","database":"archaism_dictionary","data":
[
{"id":"0","word":"wordOne","synonym":null,"definition":"defOne"},
{"id":"1","word":"wortTwo","synonym":null,"definition":"defTwo"}
]
}
]
My goal is to get a string output for each "word" and each "definition". I have the following class which corresponds to the JSON file:
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string type { get; set; }
public string version { get; set; }
public string comment { get; set; }
public string name { get; set; }
public string database { get; set; }
public Datum[] data { get; set; }
}
public class Datum
{
public string id { get; set; }
public string word { get; set; }
public object synonym { get; set; }
public string definition { get; set; }
}
Finally this piece of code is supposed to retrieve the first word from the table in the string result:
var list = JsonConvert.DeserializeObject<List<Dictionary.Rootobject>>(rawJSON);
string result = list[0].Property1[0].data[0].word;
The .Property[0] returns null and the program gives me a null reference exception. Where is my code faulty and how should I accomplish this task? Thank you.
EDIT:
I am not sure whether this can mess up the rawJSON string but I get it like this:
rawJSON = File.ReadAllText(FileSystem.AppDataDirectory + fileName);
# Claudio Valerio provide the right json data.
Based on my test, you could try the code below to get the word in the list.
Json daya:
{
"Property1":[
{"type":"header","version":"4.8.3","comment":"Export to JSON plugin for PHPMyAdmin"},
{"type":"database","name":"archaism_dictionary"},
{"type":"table","name":"dictionary","database":"archaism_dictionary","data":
[
{"id":"0","word":"wordOne","synonym":null,"definition":"defOne"},
{"id":"1","word":"wortTwo","synonym":null,"definition":"defTwo"}
]
}
]
}
Class from JSON data:
public class Rootobject
{
public Property1[] Property1 { get; set; }
}
public class Property1
{
public string type { get; set; }
public string version { get; set; }
public string comment { get; set; }
public string name { get; set; }
public string database { get; set; }
public Datum[] data { get; set; }
}
public class Datum
{
public string id { get; set; }
public string word { get; set; }
public object synonym { get; set; }
public string definition { get; set; }
}
Code:
string rawJSON = #"{
'Property1':[
{'type':'header','version':'4.8.3','comment':'Export to JSON plugin for PHPMyAdmin'},
{'type':'database','name':'archaism_dictionary'},
{'type':'table','name':'dictionary','database':'archaism_dictionary','data':
[
{'id':'0','word':'wordOne','synonym':null,'definition':'defOne'},
{'id':'1','word':'wortTwo','synonym':null,'definition':'defTwo'}
]
}
]
}";
var list = JsonConvert.DeserializeObject<Rootobject>(rawJSON);
string result = list.Property1[2].data[0].word;
It is more likely that your input json is something like this:
[
{"type":"header","version":"4.8.3","comment":"Export to JSON plugin for PHPMyAdmin"},
{"type":"database","name":"archaism_dictionary"},
{"type":"table","name":"dictionary","database":"archaism_dictionary","data":
[
{"id":"0","word":"wordOne","synonym":null,"definition":"defOne"},
{"id":"1","word":"wortTwo","synonym":null,"definition":"defTwo"}
]
Note square brakets, they're important.
If I guessed it right, you'll want to deserialize like this:
var list = JsonConvert.DeserializeObject<List<Class1>>(rawJSON);
string result = list[2].data[0].word;
Note: your original code would work only if your input json were:
{
"Property1":[
{"type":"header","version":"4.8.3","comment":"Export to JSON plugin for PHPMyAdmin"},
{"type":"database","name":"archaism_dictionary"},
{"type":"table","name":"dictionary","database":"archaism_dictionary","data":
[
{"id":"0","word":"wordOne","synonym":null,"definition":"defOne"},
{"id":"1","word":"wortTwo","synonym":null,"definition":"defTwo"}
]
}
]
}
and use
var myRoot = JsonConvert.DeserializeObject<RootObject>(rawJSON);
string result = myRoot.Property1[2].data[0].word;
You need to null handle(json NullValueHandling) below is my code please take a look :
string stringJson = #"{
'Property1':[
{'type':'header','version':'4.8.3','comment':'Export to JSON plugin for PHPMyAdmin'},
{'type':'database','name':'archaism_dictionary'},
{'type':'table','name':'dictionary','database':'archaism_dictionary','data':
[
{'id':'0','word':'wordOne','synonym':null,'definition':'defOne'},
{'id':'1','word':'wortTwo','synonym':null,'definition':'defTwo'}
]
}
]
}";
try
{
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
var list = JsonConvert.DeserializeObject<BaseResponse>(stringJson,settings);
string result = list.Property1[2].data[0].word;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Models :
public class WordData
{
public string id { get; set; }
public string word { get; set; }
public object synonym { get; set; }
public string definition { get; set; }
}
public class PropertyData
{
public string type { get; set; }
public string version { get; set; }
public string comment { get; set; }
public string name { get; set; }
public string database { get; set; }
public List<WordData> data { get; set; }
}
public class BaseResponse
{
public List<PropertyData> Property1 { get; set; }
}
I hope it will help you
Thanks
I have a code REST API response which is json, and parsing to JObject and pulling a value from it. But i am getting the error when parsing to JObject.
Error: "Unexpected character encountered while parsing value: S. Path '', line 0, position 0."
Is there any other way to convert Json string to C# object.
I have the following code:
using Newtonsoft.Json;
using (HttpResponseMessage message = httpclient.GetAsync(folderIdURL).Result)
{
if(message.IsSuccessStatusCode)
{
var dataobjects = message.Content.ReadAsStringAsync();
//dataobjects = "{"id":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/","title":"DQL query results","author":[{"name":"EMC Documentum"}],"updated":"2019-05-02T15:19:52.508+00:00","page":1,"items-per-page":100,"links":[{"rel":"self","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/?dql=SELECT%20r_object_id%2cobject_name%20FROM%20dm_sysobject%20WHERE%20FOLDER%20(%27%2fgbc%2fUS%2fOSA-ATTACHMENT%2f2019%27)"}],"entries":[{"id":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/?dql=SELECT%20r_object_id%2cobject_name%20FROM%20dm_sysobject%20WHERE%20FOLDER%20(%27%2fgbc%2fUS%2fOSA-ATTACHMENT%2f2019%27)&index=0","title":"0b0111738011c114","updated":"2019-05-02T15:19:52.508+00:00","published":"2019-05-02T15:19:52.508+00:00","links":[{"rel":"edit","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/objects/0b0111738011c114"}],"content":{"json-root":"query-result","definition":"https://gbc-dev5.cloud.wc.com/DctmRest/repositori es/dmgbsap_crt/types/dm_sysobject","properties":{"r_object_id":"0b0111738011c114","object_name":"04"},"links":[{"rel":"self","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/objects/0b0111738011c114"}]}},{"id":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/?dql=SELECT%20r_object_id%2cobject_name%20FROM%20dm_sysobject%20WHERE%20FOLDER%20(%27%2fgbc%2fUS%2fOSA-ATTACHMENT%2f2019%27)&index=1","title":"0b0111738011c115","updated":"2019-05-02T15:19:52.509+00:00","published":"2019-05-02T15:19:52.509+00:00","links":[{"rel":"edit","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/objects/0b0111738011c115"}],"content":{"json-root":"query-result","definition":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/types/dm_sysobject","properties":{"r_object_id":"0b0111738011c115","object_name":"05"},"links":[{"rel":"self","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/objects/0b0111738011c115"}]}}]}"
JObject responseObj = JObject.Parse(dataobjects.ToString());
String id = (String)responseObj["entries" -->"content"-->"properties"-->"object_name"];
}
}
}
I am expecting the value from (String)responseObject["enteries"]["content"][" properties"]["object_name"]
JObjects are a pain. You could get a sample of the JSON response and paste it into a converter like json2csharp.com. It will generate a class for you which you can then use like so:
Generated Class:
public class MyClass
{
public string SomeProperty { get; set; }
public string AnotherProperty { get; set; }
}
Usage:
if (message.IsSuccessStatusCode)
{
var deserializedObject = JsonConvert.DeserializeObject<MyClass>(response.Content.ReadAsStringAsync().Result);
Console.WriteLine(deserializedObject.SomeProperty);
}
I would suggest to follow those steps:
You need to check that your json is actually a json, because an error says it is not. You can use online tools like this
If possible, avoid JObject and generate real classes. It is not that hard if you know the structure, and you can use another online tools
Modify your code to use classes
so you will have something like:
using System;
using Newtonsoft.Json;
namespace ConsoleApp11
{
class Program
{
public class Message
{
public Enteries enteries { get; set; }
}
public class Enteries
{
public Content content { get; set; }
}
public class Content
{
public Properties properties { get; set; }
}
public class Properties
{
public string object_name { get; set; }
}
static void Main(string[] args)
{
var input = "{\"enteries\":{\"content\":{ \"properties\":{ \"object_name\":\"your value string\"}}}}";
Message msg = JsonConvert.DeserializeObject<Message>(input);
Console.WriteLine(msg?.enteries?.content?.properties?.object_name ?? "no value");
Console.ReadKey();
}
}
}
I hope it helps 😊
Thank you so much for all the help and trips. Finally i am able to get the required value from JSON string.
Here is the Final code json2csharp.com
public class Author
{
public string name { get; set; }
}
public class Link
{
public string rel { get; set; }
public string href { get; set; }
}
public class Link2
{
public string rel { get; set; }
public string href { get; set; }
}
public class Properties
{
public string r_object_id { get; set; }
public string object_name { get; set; }
}
public class Link3
{
public string rel { get; set; }
public string href { get; set; }
}
public class Content
{
public string json_root { get; set; }
public string definition { get; set; }
public Properties properties { get; set; }
public List<Link3> links { get; set; }
}
public class Entry
{
public string id { get; set; }
public string title { get; set; }
public DateTime updated { get; set; }
public DateTime published { get; set; }
public List<Link2> links { get; set; }
public Content content { get; set; }
}
public class RootObject
{
public string id { get; set; }
public string title { get; set; }
public List<Author> author { get; set; }
public DateTime updated { get; set; }
public int page { get; set; }
public int items_per_page { get; set; }
public List<Link> links { get; set; }
public List<Entry> entries { get; set; }
}
Using Newtonsoft.Json
First get the list of entries from the responseObj. Then loop each entries and use LINQ to JSON to get values by property name or index.
You can use Item[Object] index on JObject/JArray and then cast the returned JValue to the type you want
JObject responseObj = JObject.Parse(dataobjects.ToString());
// get JSON result objects into a list
IList<JToken> entries = responseObj ["entries"].Children().ToList();
foreach(JToken entry in entries)
{
string object_name = (string) entry["content"]["properties"]["object_name"];
}