I have a problem with deserializing a Json-string to an object.
This is a sample json i receive from a webservice:
{
"GetDataResult":
"{
\"id\":1234,
\"cityname\":\"New York\",
\"temperature\":300,
}"
}
And I have a class CityData that looks like this
[JsonObject("GetDataResult")]
public class CityData
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("cityname")]
public string CityName { get; set; }
[JsonProperty("temperature")]
public int Temperature { get; set; }
}
I try to deserialize the json with a call of the method DeserializeObject
var cityData = JsonConvert.DeserializeObject<CityData>(response);
but the root element seems to make problems...
Do you guys know how I can fix it, so that I receive a CityData-object with the data filled in?
The json response contains an object that within itself contains a json string representing the data result.
You need to deserialize twice, once for the response and one more for the data result.
var response = JsonConvert.DeserializeObject<JObject>(responseStr);
var dataResult = (string)response["GetDataResult"];
var cityData = JsonConvert.DeserializeObject<CityData>(dataResult);
Related
I have a JSON from an API,
{
"Cards":[
{
"ContentType":3,
"Content":"robgra"
},
{
"ContentType":4,
"Content":"Rob Graham"
},
{
"ContentType":1,
"Content":"https://www.mineralblue.net/images/robgra.jpg"
}
]
}
And i am trying to deserialize it in my .razor page. So far I have deserialized it into a string using,
using var responseStream = await response.Content.ReadAsStreamAsync();
APIreturn = await JsonSerializer.DeserializeAsync<string>(responseStream);
But i want to break it up into ConntentType and Content, i've been trying to save it as an IEnumerable object, but i keep getting an error saying the input does not contain any JSON tokens.
For example my code looks like,
Deserialized = await JsonSerializer.DeserializeAsync<IEnumerable<MyObject>>(responseStream);
But i can't figure out how to format my public class object so that i can successfully deserialize it and access individual classes.
I've tried using [JsonPropertyName("Cards"] but it didn't work. How would i format my object so i can deserialize this JSON?
Let VS do the work. Copy your JSON to a class file and use Edit | Paste Special | Paste JSON as classes and ....
public class Rootobject
{
public Card[] Cards { get; set; }
}
public class Card
{
public int ContentType { get; set; }
public string Content { get; set; }
}
I have a a api response from Azure Ml which returns the follow json bellow:
responseApi content
{ "Results": { "id_unidade_negocio": [ { "msgSucesso": "Processamento concluĂdo com sucesso" } ] } }
I would like to extract only the "msgSucesso": "Processamento concluĂdo com sucesso"
I try the code below, however didn't work.
var obj = JObject.Parse(responseApi);
var msg = (string)obj.SelectToken("Results.msgSucesso");
I didin't try to deserialize the json to a object class, because I don't know the right format class to create it to be compatible with output json.
Whats is the best way to extract this info from json response?
Or How can I create a class that fit in this json output in other to convert the json to object?
https://stackoverflow.com/a/24233127/2906166
check above link
public class IdUnidadeNegocio
{
public string msgSucesso { get; set; }
}
public class Results
{
public List<IdUnidadeNegocio> id_unidade_negocio { get; set; }
}
public class RootObject
{
public Results Results { get; set; }
}
var obj = JsonConvert.DeserializeObject<RootObject>(responseApi);
Console.WriteLine(obj.Results.First().msgSucesso);
By using below code i am calling api and trying to deserialize. I have replaced string to json format as like below,
//Code to get string response from api
var client = new WebClient();
client.Credentials = new NetworkCredential(userName, passWord);
client.Headers.Add(headerKey, headerValue);
client.QueryString.Add("companynumber", companyNumber);
var response = client.DownloadString(customerAPI);
response = response.Replace("\"", "").Replace("\\", "\"");
var results = JsonConvert.DeserializeObject<List<ProjectResponse>>(response);
output json result
"\"[{\\"data\\":{\\"closed\\":false,\\"companynumber\\":\\"430\\",\\"customernumber\\":\\"430\\\\"INTERNAL\\"}},{\\"data\\":{\\"closed\\":false,\\"companynumber\\":\\"430\\",\\"customernumber\\":\\"430INTERNAL\\"}}]"
And the respective deserialize class is below,
public class Project
{
public Nullable<long> CompanyNumber { get; set; }
public string CustomerNumber { get; set; }
public bool Closed { get; set; }
}
public class ProjectResponse
{
public Project data { get; set; }
}
In this example i am getting two list, in the first one customernumber has \\"430\\\\"INTERNAL\\ double quotes and backslash value so this is not allowing me deserialize to my respective class.so how to deserialize string eventhough one of the column has double quotes in it.
The code has be serialized twice. A model was serialized to JSON and then the JSON string was serialized again.
To fix you need to do the reverse.
var response = client.DownloadString(customerAPI);
var json = JsonConver.DeserializeObject<string>(response);
var projects = JsonConvert.SeseializeObject<List<ProjectResponse>>(json);
I am new to C# and trying to write some code to fetch the webpage and parse it into readable format.
I have fetched the data from webpage using uri
var uri2 = new Uri("explame.com")
I see the response in format below like this:
{"name":"abc" "country":"xyz" "citizenship":"A" [{"pincode":"111", "Dis":"no"] Lot's of data follows something like that
There are multiple with attribute "name" and "country" in response. My question is how to fetch the data something like below
name:abc
country:xyz
citizenshih:A
pincode 111
dis:no
For all attributes in response code.
Is that the exact format of the data you're getting? Because that's JSON-ish, but it's not valid JSON and wouldn't be parsed as such. If, however, you are actually getting JSON then you can de-serialize that.
Using something like Newtonsoft's JSON library you can fairly trivially de-serialize JSON into an object. For example, this JSON:
{
"name":"abc",
"country":"xyz",
"citizenship":"A",
"someProperty": [
{
"pincode":"111",
"Dis":"no"
}]
}
Might map to these types:
class MyClass
{
public string Name { get; set; }
public string Country { get; set; }
public string Citizenship { get; set; }
public IEnumerable<MyOtherClass> SomeProperty { get; set; }
}
class MyOtherClass
{
public string Pincode { get; set; }
public string Dis { get; set; }
}
In which case de-serializing might be as simple as this:
var myObject = JsonConvert.DeserializeObject<MyClass>(yourJsonString);
you could try
dynamic data = JsonConvert.DeserializeObject(receivedJsonString);
foreach (dynamic o in data)
{
Debug.WriteLine(o.country);
}
my json string data is
string r= "{"data":
[
{"ForecastID":54239761,"StatusForecast":"Done"},
{"ForecastID":54240102,"StatusForecast":"Done"},
{"ForecastID":54240400,"StatusForecast":"Done"},
{"ForecastID":54240411,"StatusForecast":"Done"},
{"ForecastID":54240417,"StatusForecast":"Done"}
]
}"
and my json class is
public class Datum
{
public string ForecastID { get; set; }
public string StatusForecast { get; set; }
}
public class RootObject
{
public List<Datum> data { get; set; }
}
i run this code
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Datum> ListAnswers = serializer.Deserialize<List<Datum>>(r);
Console.WriteLine("\n Deserialize: \n" + ListAnswers.Count );
and have 0 count of ListAnswers.Count
but should be 5 pieces.
what wrong? how to properly deserialize json string?
You need to deserialize an instance of RootObject.. since it is the root of the data. What you're trying to do right now is deserialize the whole thing as a list.. which it isn't. Its a root object with a list underneath it:
RootObject obj = serializer.Deserialize<RootObject>(r);
foreach (var item in obj.data) {
Console.WriteLine("\n Deserialize: \n" + item.ForecastID);
}
It looks like your JSON string is an object, not an array. In order to parse JSON directly into List, the JSON should be an array.
So, in your example above, if you modified your JSON string to be
[
{"ForecastID":54239761,"StatusForecast":"Done"},
{"ForecastID":54240102,"StatusForecast":"Done"},
{"ForecastID":54240400,"StatusForecast":"Done"},
{"ForecastID":54240411,"StatusForecast":"Done"},
{"ForecastID":54240417,"StatusForecast":"Done"}
]
it would parse as you are expecting it to be.
Another option would be to create a secondary C# class to reflect the structure of the JSON. Something along these lines:
public class DataContainer
{
public List<Datum> Data {get;set;}
}
This provides the 'data' property that is contained within your JSON string, so the serializer would populate the Data property with the list of Datum objects. Your calling code would then look like this:
JavaScriptSerializer serializer = new JavaScriptSerializer();
DataContainer results = serializer.Deserialize<DataContainer>(r);
Console.WriteLine("\n Deserialize: \n" + results.Data.Count );