I'm getting the JSON output as follows:
{"data":
[
{
"name":"followersQuery",
"fql_result_set":[{"subscriber_count":300}]
},
{
"name":"likesQuery",
"fql_result_set":[{"like_count":0}]
}
]
}
It is the output of multiple fql query.
I have created the following classes to deserialize the output:
public class ResultCount
{
[JsonProperty("subscriber_count")]
public int Followers { get; set; }
[JsonProperty("like_count")]
public int Likes { get; set; }
}
public class ResultItem
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("fql_result_set")]
public ResultCount ResultCounts { get; set; }
}
public class FacebookData
{
public List<ResultItem> Items { get; set; }
}
I'm getting error while de-serializing the output in the following line:
JsonConvert.DeserializeObject<FacebookData>(myOutput);
The error is:
The best overloaded method match for
'Newtonsoft.Json.JsonConvert.DeserializeObject(string)'
has some invalid arguments.
Not able to correct this. Can anyone please correct this?
Many many thanks in advance!
ResultCounts return type should be List<Resultcount>.
Change
public ResultCount ResultCounts { get; set; }
to
public List<ResultCount> ResultCounts { get; set; }
On a sidenote you can get class structue by simply pasting your json here - Json2csharp. It will automatically generate class structure for you. It can be use to validate your structure. Generated structure was like this:
public class FqlResultSet
{
public int subscriber_count { get; set; }
public int? like_count { get; set; }
}
public class Datum
{
public string name { get; set; }
public List<FqlResultSet> fql_result_set { get; set; }
}
public class RootObject
{
public List<Datum> data { get; set; }
}
Related
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"];
}
I was experiencing some to deserilize a json file until I realized the reason was that the file was formatted, prettified, beautified etc.
Using Newtonsoft.Json library and calling
JsonConvert.DeserializeObject<myObject>(mystring);
throws a JsonSerializationException:
{"Unexpected end when reading JSON. Path '', line 1, position 1."}
Then, when I repeated the operation, but with a minified, compacted, etc version of the same file it worked.
Is there a way to use this libray and deserialize data in both scenarios?
Thank you!
Your json is Valid, your model should be like this
public class Step
{
public int StepID { get; set; }
public string Description { get; set; }
public List<int> ShutMoves { get; set; }
public List<int> FeatIDs { get; set; }
public List<int> ExpSettings { get; set; }
}
public class Part
{
public int PartID { get; set; }
public string Description { get; set; }
public bool Moving { get; set; }
public List<int> FeatIDs { get; set; }
}
public class Feat
{
public int FeatID { get; set; }
public int CamID { get; set; }
public int CamFeatID { get; set; }
public int PartID { get; set; }
}
public class RootObject
{
public List<Step> Steps { get; set; }
public List<Part> Parts { get; set; }
public List<Feat> Feats { get; set; }
}
Small Example -
public void JsonDeserializeTesting() {
var testingModal = new TestingModal{Id = 1,Name = "Eminem",};
var serializeObject = JsonConvert.SerializeObject(testingModal);
var deserializeObject = JsonConvert.DeserializeObject<TestingModal>
(serializeObject);
Console.WriteLine($"{deserializeObject}");
}
public class TestingModal{
public long Id { get; set; }
public string Name { get; set; }
}
I hope this will give you abstract view of how to use Deserialize.
This was a mistake from my side. The string I was deserializing was obtained by using ReaLine(). So my code was parsing only the first line of the file.
ReadToEnd() from the stream or even File.ReadAllText fixes the issue.
Thank you for the help.
I get the following JSON response.
[
{
"Issue": {
"ID": 80,
"Name": "Cold",
"Accuracy": 90,
"Icd": "J00",
"IcdName": "Acute nasopharyngitis [common cold]",
"ProfName": "Common cold",
"Ranking": 1
},
"Specialisation": [
{
"ID": 15,
"Name": "General practice",
"SpecialistID": 0
}
]
}
]
I tried to follow the instructions given here. But I can't seem to fit that solution here. And in the documentation is explained only the scenario where you already have the class predefined. Any help?
Presumptions
Your question is not even clear. What are you asking? I presume you are asking how to make a C# class from that JSON?
Solution
Firstly, the JSON is an array (if its top-level tags are [] its an array itself. If its top level is {} then its a single object.
So what you have is an array returned with one result inside of it.
Going to json2csharp and pasting your code gives this:
public class Issue
{
public int ID { get; set; }
public string Name { get; set; }
public int Accuracy { get; set; }
public string Icd { get; set; }
public string IcdName { get; set; }
public string ProfName { get; set; }
public int Ranking { get; set; }
}
public class Specialisation
{
public int ID { get; set; }
public string Name { get; set; }
public int SpecialistID { get; set; }
}
public class RootObject
{
public Issue Issue { get; set; }
public List<Specialisation> Specialisation { get; set; }
}
And you can see its created a RootObject almost indicating it is a single object, but you will need to deserialize this as a List<RootObject> not just RootObject.
So in C# that would be var result = JsonConvert.DeserializeObject<List<RootObject>>(theJsonString);
You should have a strongly typed c# class ready for your Json Response to be deserialized into... Json Utils has a generator to use, it came up with this:
public class Issue
{
[JsonProperty("ID")]
public int ID { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("Accuracy")]
public int Accuracy { get; set; }
[JsonProperty("Icd")]
public string Icd { get; set; }
[JsonProperty("IcdName")]
public string IcdName { get; set; }
[JsonProperty("ProfName")]
public string ProfName { get; set; }
[JsonProperty("Ranking")]
public int Ranking { get; set; }
}
public class Specialisation
{
[JsonProperty("ID")]
public int ID { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("SpecialistID")]
public int SpecialistID { get; set; }
}
public class RootObject
{
[JsonProperty("Issue")]
public Issue Issue { get; set; }
[JsonProperty("Specialisation")]
public IList<Specialisation> Specialisation { get; set; }
}
Then use
RootObject jsonAsCSharpClass = JsonConvert.DeserializeObject<RootObject>(jsonResponse);
I'm not 100% sure this class is good for you though, i have never some across a response where the root response is an array, without defining a root property first, see how it starts with "[" instead of { ??? You may want to also try
List<RootObject> jsonAsCSharpClass = JsonConvert.DeserializeObject<List<RootObject>>(jsonResponse);
Or wait for someone with more knowledge on the subject to come along...
I am getting the below JSON in response from a REST API.
{
"data":{
"id":123,
"zoneid":"mydomain.com",
"parent_id":null,
"name":"jaz",
"content":"172.1 6.15.235",
"ttl":60,
"priority":null,
"type":"A",
"regions":[
"global"
],
"system_record":false,
"created_at":"2017-09-28T12:12:17Z",
"updated_at":"2017-09-28T12:12:17Z"
}
}
and trying to resolve using below code but that doesn't result in a correctly deserialized type.
var model = JsonConvert.DeserializeObject<ResponseModel>(response);
below is a class according the field I received in JSON response.
public class ResponseModel
{
public int id { get; set; }
public string zone_id { get; set; }
public int parent_id { get; set; }
public string name { get; set; }
public string content { get; set; }
public int ttl { get; set; }
public int priority { get; set; }
public string type { get; set; }
public string[] regions { get; set; }
public bool system_record { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
}
What is missing?
You're missing a wrapper class.
public class Wrapper
{
public ResponseModel data {get;set}
}
and then do:
var model = JsonConvert.DeserializeObject<Wrapper>(response).data;
to get the instance of your ResponseModel out the data property.
You can deduct this from your json:
{ "data":
{ "id":123, /*rest omitted */ }
}
The type that will receive this JSON needs to have a property named data. The suggested Wrapper class acts as that type.
According to json2csharp website, your model seems to be incorrect. Try this one :
public class ResponseModel
{
public int id { get; set; }
public string zoneid { get; set; }
public object parent_id { get; set; }
public string name { get; set; }
public string content { get; set; }
public int ttl { get; set; }
public object priority { get; set; }
public string type { get; set; }
public List<string> regions { get; set; }
public bool system_record { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
}
public class RootObject
{
public ResponseModel data { get; set; }
}
Here a cool trick you can do in Visual Studio 2015-2017 where it generates the the correct class if you just copy the JSON (ctrl + c).
You need to create a new class in visual studio and once inside the class go to Edit menu -> Paste special -> paste JSON As Classes.
Steps to generate json class
This will generate the C# object for that json for you and save you all the hassle :)
Your model does not match your response - it matches the data property. Simply wrap another object round it
public class ResponseData
{
public ResponseModel Data {get; set; {
}
and then
var model = JsonConvert.DeserializeObject<ResponseData>(response);
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.