How to deserialize Json to an object? - c#

I want to convert json to a specific object.
String : "{\r\n \"Status\": \"PLANNED\"\r\n}"
I tried Newtonsoft Json namespace but it is returning a null value.
var Json= Newtonsoft.Json.JsonConvert.DeserializeObject<Model Class>(String )
I want the result in Json format so that I can extract the value from Json as "PLANNED" but I am getting a null.
PS :The model class contains two properties , Name (type of string), Value(type of Object)

var s = "{\r\n \"Status\": \"PLANNED\"\r\n}";
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<StatusModel>(s);
The model you have defined is incorrect.
Your model should be like this:
public class StatusModel
{
public string Status { get; set; }
}
Now value will be extracted to this model and you can access the value like:
var value = obj.Status; //"PLANNED"

JSON Definition
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language.
[Source] https://www.json.org/
JSON Newtonsoft
Json.NET is a popular high-performance JSON framework for .NET .
[Source] https://www.newtonsoft.com/json
Problem :
Your are trying to deserialize a json to an object and it's returning a null.
In our context a Deserialization is process which transform a json to an object .
var Result= Newtonsoft.Json.JsonConvert.DeserializeObject<Model Class>(String);
The reason why you have a Null as result is beacause you are deserializing a json to Model, knowing that you Json does not correspond to the Model , this is why the Json need to correspond to the Model so that it can store the information of the Json.
Your Model :
The model may contain some property that are not in the json and vice versa
public class StatusModel
{
public string Status { get; set; }
}
Best Regards .

You can do it like this (using Newtonsoft Framework)
using System;
using Newtonsoft.Json;
{
public class JsonHandler : IJsonHandler
{
public IJsonModel ReadJson(IJsonModel model, StreamReader reader)
{
try
{
string jsonFromFile;
using (reader))
{
jsonFromFile = reader.ReadToEnd();
}
status = JsonConvert.DeserializeObject<model>(jsonFromFile);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return status;
}
}
}

Related

Retuning JObject\dynamic with ServiceStack seems to return

I'm trying to take a JSON string from SQL (works fine with SQL json queries, it's stuctured fine in there) and return it through ServiceStack. There's no errors on deserializing it, I can see the object in debug, but the result from the service is just a bunch of blank nested arrays?
//Tried both of these, same result
this.Json = JObject.Parse(json);
/// or
this.Json = JsonConvert.DeserializeObject<dynamic>(json);
///....
public dynamic Json { get; set; }
/// or
public JObject Json { get; set; }
Can't do a POCO because I don't know the structure, just need to poop back out the json blob.
See Service Return Types and Customize HTTP Responses for different ways to return custom responses in ServiceStack.
If you just want to return the JSON from SQL Server as-is, you can return the json string with the JSON Content Type, e.g:
[AddHeader(ContentType = MimeTypes.Json)]
public string Get(RawJson request)
{
//...
return json;
}
Or use a HttpResult if you need to add additional HTTP Headers:
public string Get(RawJson request)
{
return new HttpResult(json) {
ContentType = MimeTypes.Json,
Headers = {
[HttpHeaders.XXX] = "..."
}
};
}
Either way you should annotate your Request DTO that it returns a string so clients know to return the string response as-is:
public class RawJson : IReturn<string> {}
If you want to return the JSON object as part of a larger payload you can use JS Utils JSON.parse() to parse arbitrary JSON in untyped generic collections, e.g:
public string Get(CustomJson request)
{
return new CustomJsonResponse {
Result = JSON.parse(json)
};
}
Where Result is an object, using object does mean that it wont be supported with Add ServiceStack Reference typed clients and clients would just need to parse it as arbitrary JSON, e.g. JSON.parse(json) in JavaScript.

Deserializing an api call response content without having to create a model representing the content

Is there another way to deserialize the response content of an api call into a generic object in .Net without having to create a model representing the json object? In other words, is there or does .Net provide a generic object or model that i can use to deserialize the response into. The reason being is because every api call response is not the same which means i have to create a new model for every api call. And i have about 20 different endpoints that return different responses, which means i would have to create 20 models representing the response.
My recommendation would be to create request and response models for this, even though it feels like extra work. This is because you'll need to eventually pass the parameters to functions in your business layer anyway, and you'll want to take advantage of the type safety without doing a bunch of Int32.TryParse's, which at that point, you're creating variables and doing extra work anyway. Actually, you're not going to be able to outrun the type safety the language not only provides, but generally requires. What I've done, is just copy/paste my DTO or EDMX table model into the new class, then decorate it. Pretty fast.
You may be looking for dynamic object which is late bound with unknown compile time properties.
A handy implementation of this is the JObject available with Newtonsoft.Json package and it offers similar functionality to the typeless elements of Javascript in that the properties can be of any type, with any nesting, etc. as long as it was parsed from well formed Json.
Usage is super simple, but watch out for null values, etc as default behavior for dynamic (aka ExpandoObject under the hood) is to throw exceptions for properties (aka Keys) not found...
public static void Run()
{
string apiJsonResponse = #"{
Name: 'Luke Skywalker',
Title: 'Jedi',
Skills : [
'Lightsaber',
'The Force'
]
}";
dynamic json = JObject.Parse(apiJsonResponse);
Console.WriteLine($"Name: {json.Name}");
Console.WriteLine($"Title: {json.Name}");
Console.WriteLine($"Skills: {String.Join(", ", json.Skills)}");
}
The result will be the Json dynamically parsed and rendered without any strongly typed model:
You can use generic method to have list of JObject. Based on your need you can extract model from jobject.
private static async Task<List<JObject>> CallApi(Uri uri, HttpContent data = null, string headerKey = null, string headerKeyVal = null)
{
string res = string.Empty;
try
{
var handler = new HttpClientHandler
{
//UseDefaultCredentials = true,
};
using var client = new HttpClient(handler);
if (!string.IsNullOrWhiteSpace(headerKey))
client.DefaultRequestHeaders.Add(headerKey, headerKeyVal);
var post = await client.GetAsync(uri);
//var post = await client.PostAsync(uri);
if (post.StatusCode != HttpStatusCode.InternalServerError)
{
res = await post.Content.ReadAsStringAsync();
}
return JsonConvert.DeserializeObject<List<JObject>>(res);
}
catch (Exception ex)
{
throw ex;
}
}
in .Net 3.1 after version, can use using System.Text.Json
api response data
{
"Status" : "0"
"Data" : {
"FirstName" : "firstName",
"LastName" : "lastName"
}
}
Response Model
public class ResponseModel
{
public string Status { get; set; }
public JsonElement Data { get; set; }
}
Deserialize
public void Deserialize()
{
var jsonString = "{ \"Status\": \"0\", \"Data\": { \"FirstName\": \"firstName\", \"LastName\" : \"last_name\"} }";
var response = JsonSerializer.Deserialize<ResponseModel>(jsonString);
//get first_name
var firstName = response.Data.GetProperty("FirstName").GetString();
Console.WriteLine(firstName);
}

How do I deserialize this JSON array (C#)

I am struggling with a subject that has a lot of variants, but I can't seem to find one that works for me, and I think it's because of the way that my JSON array is.
I'm not an expert in C# or JSON, but I already manage to "almost" get this to work. I need to get hand with the class that the JSON will deserialize to.
When I run the code I dont get an error, just a nulls in the xKisokData var.
The JSON data that I am getting. Their are these two different ones.
"{\"Event\": \"sConnection\",\"data[device]\": \"fb16f550-2ef1-11e5-afe9-ff37129acbf4\",\"data[mode]\": \"customer\",\"data[starttime]\": \"2015-07-22T16:07:42.030Z\",\"data[endtime]\": \"\"}"
"{\"Event\": \"Log\",\"data[id]\": \"2015-07-22T16:07:23.063Z\",\"data[messages][0][source]\": \"server\",\"data[messages][0][message]\": \"Server is listening on port 1553\"}"
The code I have so far:
// Read in our Stream into a string...
StreamReader reader = new StreamReader(JSONdataStream);
string JSONdata = reader.ReadToEnd();
JavaScriptSerializer jss = new JavaScriptSerializer();
wsKisokData[] xKisokData = jss.Deserialize<wsKisokData[]>(JSONdata);
My Class:
namespace JSONWebService
{
[DataContract]
[Serializable]
public class KisokEvent
{
public string eventTrigger { get; set; }
}
[DataContract]
[Serializable]
public class KisokData
{
public string data { get; set; }
}
[DataContract]
[Serializable]
public class wsKisokData
{
public KisokEvent KDEvent { get; set; }
public List<KisokData> KDData { get; set; }
}
}
I am sure that I don't understand the Deserialize process. Thanks for the help.
EDIT:
I put the JSON in the top part right from the debugger, here is the strings.
{
"Event": "sConnection",
"data[device]": "fb16f550-2ef1-11e5-afe9-ff37129acbf4",
"data[mode]": "customer",
"data[starttime]": "2015-07-22T16:07:42.030Z",
"data[endtime]": ""
}
{
"Event": "Log",
"data[id]": "2015-07-22T16:07:23.063Z",
"data[messages][0][source]": "server",
"data[messages][0][message]": "Server is listening on port 1553"
}
I would HIGHLY recommend using the json.net package off nuget instead.
You can generate template classes (models) for it by pasting the json into http://json2csharp.com/
Then use said models to convert the json into a c# object (deserializing) by doing a
var jsonStructure = JsonConvert.DeserializeObject<model>(json)
And query as if it was just a standard object
foreach (var x in jsonStructure.KDData)
{
doAction(x.data);
}
// for example

Null value after json deserialization on windows phone

I am using the Json.DeserializeObject method in windows phone, inorder to deserialize json, the problem I am having is one of the variable names, in the json has a space and I just can't get it to deserialize. it returns a null the whole time, and if I view the raw json it does contain a value
part of raw json:
\"Service Provider\":Test\"
When I try to generate a class for the json into which it needs to be deserialized, the Service Provider section tells me "Invalid Name" and that obviously doesn't work in C# as a variable name, but I believe the variable name can be anything:
public string __invalid_name__Service Provider { get; set; }
current code:
public string Service_Provider { get; set; }
Using Json.Net, Just decorate your property with "JsonProperty" Attribute
string json = #"{""Service Provider"":""Test""}";
var obj = JsonConvert.DeserializeObject<TempObject>(json);
public class TempObject
{
[JsonProperty("Service Provider")]
public string ServiceProvider;
}

RestSharp: Converting results

I get the following JSON that I am trying to convert to a business object using RestSharp
{
"valid":true,
"data":[
{
"dealerId":"4373",
"branchId":"4373",
}
]
}
I wish to convert to:
public class Dealer
{
public string dealerId ;
public string branchId;
}
But this fails, though the JSON is fine:
var client = new RestClient("http://www.????.com.au");
var request = new RestRequest(string.Format("service/autocomplete/dealer/{0}/{1}.json", suburb.PostCode, suburb.City.Trim().Replace(" ", "%20")), Method.GET);
var response2 = client.Execute<Dealer>(request);
return response2.Data;
Your business object doesn't match the response JSON you are getting back. If you want your response to serialize, your C# object would look something like
public class DealerResponse
{
public bool valid { get;set; }
List<Dealer> data { get;set; }
}
public class Dealer
{
public string dealerId;
public string branchId;
}
I haven't tested this code, but even though you are only interested in the information in 'data', your response C# objects still need to represent the whole JSON response to serialize correctly.
Hope that helps.

Categories