JSON DeserializeObject shows 0 - c#

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

Related

Deserializing JSON into C# Class with dynamic object [duplicate]

This question already has answers here:
Complicated Json to C# Object Deserialize with classes
(2 answers)
Closed 7 months ago.
I have json being returned from an API. The JSON is formatted as below:
{
"success":true,
"code":200,
"total":2,
"data":{
"1019588":{
"name":"(t) Bob Jones",
"calls":213,
"user_id":"1019588"
},
"1019741":{
"name":"(t) Chris Smith",
"calls":387,
"user_id":"1019741"
}
}
}
I am trying to deserialize into a C# class but I am having issues with the dynamic id for each employee row.
My code:
AgentPeformanceResponse viewModel = JsonSerializer.Deserialize<AgentPeformanceResponse>(result.Result);
public class AgentPeformanceResponse
{
public bool success { get; set; }
public int code { get; set; }
public int total { get; set; }
public Data data { get; set; }
public AgentPeformanceResponse()
{
data = new Data();
}
}
public class Data
{
public Data()
{
PerformanceReponse = new List<PerformanceReponse>();
}
public List<PerformanceReponse> PerformanceReponse { get; set; }
}
public class PerformanceReponse
{
public string name { get; set; }
public int calls { get; set; }
public string user_id { get; set; }
}
How do I handle the dynamic employee ID so that I can deserialize it all into one object?
You should use a Dictionary:
public class AgentPeformanceResponse
{
public bool success { get; set; }
public int code { get; set; }
public int total { get; set; }
public Dictionary<string,PerformanceReponse> data { get; set; }
}
public class PerformanceReponse
{
public string name { get; set; }
public int calls { get; set; }
public string user_id { get; set; }
}
Example:
string json = #"{
""success"":true,
""code"":200,
""total"":2,
""data"":{
""1019588"":{
""name"":""(t) Bob Jones"",
""calls"":213,
""user_id"":""1019588""
},
""1019741"":{
""name"":""(t) Chris Smith"",
""calls"":387,
""user_id"":""1019741""
}
}
}";
var obj = System.Text.Json.JsonSerializer
.Deserialize<AgentPeformanceResponse>(json);
using System;
using System.Collections.Generic;
public class AgentPeformanceResponse
{
public bool success { get; set; }
public int code { get; set; }
public int total { get; set; }
public Dictionary<string, PerformanceReponse> data { get; set; }
}
public class PerformanceReponse
{
public string name { get; set; }
public int calls { get; set; }
public string user_id { get; set; }
}
public class Program
{
public static void Main()
{
var json = "{\"success\":true,\"code\":200,\"total\":2,\"data\":{\"1019588\":{\"name\":\"(t) Bob Jones\",\"calls\":213,\"user_id\":\"1019588\"},\"1019741\":{\"name\":\"(t) Chris Smith\",\"calls\":387,\"user_id\":\"1019741\"}}}";
var result = System.Text.Json.JsonSerializer.Deserialize<AgentPeformanceResponse>(json);
Console.WriteLine(result.code);
Console.WriteLine(result.data["1019741"].name);
}
}
The output will be
200
(t) Chris Smith
Fiddle for you
https://dotnetfiddle.net/lQu2Ln
all code you really need
Dictionary<string, PerformanceReponse> dict = JsonDocument.Parse(json).RootElement
.GetProperty("data").Deserialize<Dictionary<string,PerformanceReponse>>();
//or if you want a list
List<PerformanceReponse> list = data.Select(d=>d.Value).ToList();
or using Newtonsoft.Json
Dictionary<string,PerformanceReponse> dict = JObject.Parse(json)
["data"].ToObject<Dictionary<string,PerformanceReponse>>();
how to use
PerformanceReponse data1019588= dict["1019588"];

How do I compare two JSON Objects to get new JSON for changes like add,delete,change using c#

Can anyone help in getting the output Json by comparing two JSON which has same hierarchy, by showing JStatus as Change, Added, Delete. we have JStatus present in each Json, after comparison it will fill with status "change"/"add"/"delete", the values should be from new (2nd json) for changed objects, and value of old (in case of delete) json1.
please help
1st Base JSON (output should treat this as base JSON)
[{"Decision":{"id":"1","identifier":"Base1","dec_id":10,"JStatus":"","objects":[{"id":"1","identifier":"Base2","JStatus":""},{"id":"2","identifier":"Base3","JStatus":""}]}}]
2nd JSON
[{"Decision":{"id":"2","identifier":"Base1","dec_id":12,"JStatus":"","objects":[{"id":"1","identifier":"Base2","JStatus":"","textitem":[{"id":"1","identifier":"Base3","JStatus":"","objNewActivity":[{"id":"1","identifier":"Base4","JStatus":""}],"objNewGebiedsaanwijzingen":[{"id":"1","identifier":"Base5","JStatus":""}],"objNewBegrippen":[{"id":"1","identifier":"Base6","JStatus":""}],"objNewLocation":null}]}]}}]
OutPut required JSON
[{"Decision":{"id":"2","identifier":"Base1","dec_id":12,"JStatus":"Change","objects":[{"id":"1","identifier":"Base2","JStatus":"","textitem":[{"id":"1","identifier":"Base3","JStatus":"Add","objNewActivity":[{"id":"1","identifier":"Base4","JStatus":"Add"}],"objNewGebiedsaanwijzingen":[{"id":"1","identifier":"Base5","JStatus":"Add"}],"objNewBegrippen":[{"id":"1","identifier":"Base6","JStatus":"Add"}],"objNewLocation":null}]},{"id":"2","identifier":"Base3","JStatus":"Delete"}]}}]
I tried https://www.nuget.org/packages/JsonDiffer following but that only show me changes,
var j1 = JToken.Parse(readJson("Json1.txt"));
var j2 = JToken.Parse(readJson("Json2.txt"));
var diff = JsonDifferentiator.Differentiate(j1, j2, OutputMode.Detailed, showOriginalValues: true);
This is PSEUDO CODE
Because I do not know the specific logic you wish to employ to make your comparisons and/or overwrites.
using Newtonsoft.Json;
using System.Collections.Generic;
namespace StackDemo5
{
public class StackDemo5Main
{
string json1 = "{ \"LoginSettings\": { \"Type\": \"Test\", \"Login\": \"Bitcoin\", \"Password\": \"123456\", \"SHA1Login\": \"Some hash\", \"SHA1Password\": \"Some hash\" }, \"Info1\": {\"Is_Active\": false, \"Amount\": 12 }, \"Info2\": { \"Is_Active\": true, \"Amount\": 41 }}";
string json2 = "{ \"LoginSettings\": { \"Type\": \"\", \"Login\": \"\", \"Password\": \"\", \"SHA1Login\": \"\", \"SHA1Password\": \"\" }, \"Info1\": { \"Is_Active\": false, \"Amount\": 0 }, \"Info2\": { \"Is_Active\": false, \"Amount\": 0 }, \"Info3\": { \"Is_Active\": false, \"Amount\": 0 }, \"Info4\": { \"Is_Active\": false, \"Amount\": 0 }}";
public string CreateJsonAggregate() {
Root first = JsonConvert.DeserializeObject<Root>(json1);
Root second = JsonConvert.DeserializeObject<Root>(json2);
Root third = new Root();
third.LoginSettings = first.LoginSettings;
third.Info1 = first.Info1;
third.Info2 = first.Info2;
third.Info3 = second.Info3;
third.Info4 = second.Info4;
return JsonConvert.SerializeObject(third);
}
public class LoginSettings
{
public string Type { get; set; }
public string Login { get; set; }
public string Password { get; set; }
public string SHA1Login { get; set; }
public string SHA1Password { get; set; }
}
public class Info1
{
public bool Is_Active { get; set; }
public int Amount { get; set; }
}
public class Info2
{
public bool Is_Active { get; set; }
public int Amount { get; set; }
}
public class Info3
{
public bool Is_Active { get; set; }
public int Amount { get; set; }
}
public class Info4
{
public bool Is_Active { get; set; }
public int Amount { get; set; }
}
public class Root
{
public LoginSettings LoginSettings { get; set; }
public Info1 Info1 { get; set; }
public Info2 Info2 { get; set; }
public Info3 Info3 { get; set; }
public Info4 Info4 { get; set; }
}
}
public class StackDemo6 {
public string CreateJsonAggregate()
{
string input1 = "[{\"Decision\":{\"id\":\"1\",\"identifier\":\"Base1\",\"dec_id\":10,\"JStatus\":\"\",\"objects\":[{\"id\":\"1\",\"identifier\":\"Base2\",\"JStatus\":\"\"},{\"id\":\"2\",\"identifier\":\"Base3\",\"JStatus\":\"\"}]}}]";
string input2 = "[{\"Decision\":{\"id\":\"2\",\"identifier\":\"Base1\",\"dec_id\":12,\"JStatus\":\"\",\"objects\":[{\"id\":\"1\",\"identifier\":\"Base2\",\"JStatus\":\"\",\"textitem\":[{\"id\":\"1\",\"identifier\":\"Base3\",\"JStatus\":\"\",\"objNewActivity\":[{\"id\":\"1\",\"identifier\":\"Base4\",\"JStatus\":\"\"}],\"objNewGebiedsaanwijzingen\":[{\"id\":\"1\",\"identifier\":\"Base5\",\"JStatus\":\"\"}],\"objNewBegrippen\":[{\"id\":\"1\",\"identifier\":\"Base6\",\"JStatus\":\"\"}],\"objNewLocation\":null}]}]}}]";
Root input1Deserialized = JsonConvert.DeserializeObject<Root>(input1);
Root input2Deserialized = JsonConvert.DeserializeObject<Root>(input2);
Root resultObject = new Root();
// Build you comparison logic:
int dec_id;
if (input1Deserialized.Decision.dec_id > input2Deserialized.Decision.dec_id)
{
dec_id = input1Deserialized.Decision.dec_id;
}
else
{
dec_id = input2Deserialized.Decision.dec_id;
}
resultObject.Decision.dec_id = dec_id;
//etc.
return JsonConvert.SerializeObject(result);
}
}
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class ObjNewActivity
{
public string id { get; set; }
public string identifier { get; set; }
public string JStatus { get; set; }
}
public class ObjNewGebiedsaanwijzingen
{
public string id { get; set; }
public string identifier { get; set; }
public string JStatus { get; set; }
}
public class ObjNewBegrippen
{
public string id { get; set; }
public string identifier { get; set; }
public string JStatus { get; set; }
}
public class Textitem
{
public string id { get; set; }
public string identifier { get; set; }
public string JStatus { get; set; }
public List<ObjNewActivity> objNewActivity { get; set; }
public List<ObjNewGebiedsaanwijzingen> objNewGebiedsaanwijzingen { get; set; }
public List<ObjNewBegrippen> objNewBegrippen { get; set; }
public object objNewLocation { get; set; }
}
public class Object
{
public string id { get; set; }
public string identifier { get; set; }
public string JStatus { get; set; }
public List<Textitem> textitem { get; set; }
}
public class Decision
{
public string id { get; set; }
public string identifier { get; set; }
public int dec_id { get; set; }
public string JStatus { get; set; }
public List<Object> objects { get; set; }
}
public class Root
{
public Decision Decision { get; set; }
}
}
The trick is to create a generic model that can hold the most possible data, then serialize an object set from all your input strings, then do some sort of logic comparison, here I just did a comparison on dec_id, because I have no idea what your model does, and I don't speak dutch.
Also do write unit tests to validate your logic, it helps.
If you need to generate a new model object in C#, simply use this website from your template, to get a new class structure:
https://json2csharp.com/

C# - Store JSON array string into SQL table

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);

Error deserializing JSON file in Visual Studio

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

Convert Rest API JSON Response into C# object

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"];
}

Categories