Parse json string to find and element - c#

I have following json:
{
"578080":{
"success":true,
"data":{
"price_overview":{
"currency":"USD",
"initial":1799,
"final":1799,
"discount_percent":0
}
}
}
}
I want to search "initial".
How can I do this using Json.Net or any other efficient means in C#?
Note : i haven't tried anything because i am unsure where to start

Since this is a Dictionary<string,object> you can follow this, Deserialize a Dictionary
public class PriceOverview
{
public string currency { get; set; }
public int initial { get; set; }
public int final { get; set; }
public int discount_percent { get; set; }
}
public class Data
{
public PriceOverview price_overview { get; set; }
}
public class RootObject
{
public bool success { get; set; }
public Data data { get; set; }
}
var results = JsonConvert.DeserializeObject<Dictionary<string, RootObject>>(json);
foreach (var result in results)
{
Console.WriteLine(result.Key);
Console.WriteLine(result.Value.data.price_overview.currency);
Console.WriteLine(result.Value.data.price_overview.initial);
Console.WriteLine(result.Value.data.price_overview.final);
Console.WriteLine(result.Value.data.price_overview.discount_percent);
}
Output
578080
USD
1799
1799
0
Full demo here

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

JSON DeserializeObject shows 0

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

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

Deserialise a Kraken JSON in C#

I used to be loading data from Cryptocompare's API.
This post got me what I wanted for Cryptocompare.
Parsing Cryptocompare API Json data in C#
However, I notice that this API is not bulletproof, it's not always returning an answer. So I want to use Kraken itself.
Now I am trying to deserialise the new JSON but this is not straightforward as Cryptocompare's JSON.
Here is an example JSON:
https://api.kraken.com/0/public/OHLC?pair=ETHUSD&interval=30
{"error":[],"result":{"XETHZUSD":[[1519236000,"825.94","846.00","825.94","845.00","835.62","858.29381033",708],[1519237800,"846.00","848.84","835.55","836.00","844.31","647.42747317",731],[1519239600,"836.00","841.09","830.76","834.89","835.13","1051.44905097",609],[1520530200,"706.24","710.43","701.90","704.59","707.70","1763.41692283",459]],"last":1520528400}}
I have not been able to deserialise this JSON.
Solved!!!
final solution:
var Results_Exchange_Kraken = JsonConvert.DeserializeObject<DataRoot_Kraken>(Content_Exchange_Kraken);
var price_data_kraken = Results_Exchange_Kraken.result.XETHZUSD;
public class Kraken_Result
{
public List<List<object>> XETHZUSD { get; set; }
public int last { get; set; }
}
public class DataRoot_Kraken
{
public List<object> error { get; set; }
public Kraken_Result result { get; set; }
}
Thank you! I'll bookmark the URL.
Use this Model to de-serialise your data
public class Result
{
public List<List<object>> XETHZUSD { get; set; }
public int last { get; set; }
}
public class RootObject
{
public List<object> error { get; set; }
public Result result { get; set; }
}
Model Generated by Model Generator
Then use NewtonSoft for c# to de-serialise your data
E.g.
RootObject tmp = JsonConvert.DeserializeObject<RootObject>("JSON String here");
final solution:
var Results_Exchange_Kraken = JsonConvert.DeserializeObject<DataRoot_Kraken>(Content_Exchange_Kraken);
var price_data_kraken = Results_Exchange_Kraken.result.XETHZUSD;
public class Kraken_Result
{
public List<List<object>> XETHZUSD { get; set; }
public int last { get; set; }
}
public class DataRoot_Kraken
{
public List<object> error { get; set; }
public Kraken_Result result { get; set; }
}

Json not mapping properly in C#

Here is a json document that I wanted to map it to C# poco classes. I wrote some classes but they didn't work. I got null in my result object. Any ideas?
I used Newtonsoft's json converter.
{
"retrieval-response":{
"cdata":{
"identifier":"777400",
"document-count":"62"
},
"index":"10",
"count":"25"
}
}
C# map classes;
public class result
{
[JsonProperty("retrieval-response")]
public aResult res { get; set; }
public int index { get; set; }
public int count { get; set; }
}
public class aResult
{
public cdata data { get; set; }
}
public class cdata
{
[JsonProperty("identifier")]
public string identif { get; set; }
[JsonProperty("document-count")]
public string count { get; set; }
}
You model is wrong. Try this:
public class Wrapper
{
[JsonProperty("retrieval-response")]
public Result Result { get; set; }
}
public class Result
{
[JsonProperty("cdata")]
public Data Data { get; set; }
public int Index { get; set; }
public int Count { get; set; }
}
public class Data
{
[JsonProperty("identifier")]
public string Identifier { get; set; }
[JsonProperty("document-count")]
public string Count { get; set; }
}
Then you can deserialize it with the following line:
var myResult = JsonConvert.DeserializeObject<Wrapper>(json);
Please note that I've also wrote your property and class names in pascal case. These are the naming conventions from Microsoft.

Categories