Json deserialize is not working - c#

I am receiving a Json response from an API but unable to convert to object.
My class is
public class ResultOrder
{
public int id { get; set; }
public string currency { get; set; }
public string status { get; set; }
public string order_id { get; set; }
public double price { get; set; }
}
var response = await client.PostAsync(path, body);
if (response.IsSuccessStatusCode)
{
var newOrder = await response.Content.ReadAsAsync<dynamic>();
ResultOrder obj = JsonConvert.DeserializeObject(newOrder);
}
And the result i am getting from API in the variable newOrder is --
{
"id": 68456,
"currency": "USD",
"status": "pending",
"price": "79.97",
"order_id": "1233219",
}
But unable to get the deserialized result in the obj variable.

You can just do
ResultOrder obj = response.Content.ReadAsAsync<ResultOrder>()
directly. This will handle the deserialisation for you.

Following changes you need to do to deserialize the newOrder object.
ResultOrder obj = JsonConvert.DeserializeObject<ResultOrder>(newOrder);
While deserializing the object, cast to desire object in your case it is ResultOrder

Related

C# deserializator doesn't return result

i have problem with my deserialization and don't know how to deal.
var jsonString = #"
{
""Result"": [
{
""Id"": 994,
""Name"": ""LL Bottom Bracket"",
},
{
""Id"": 995,
""Name"": ""ML Bottom Bracket"",
}
]
}";
HotelRoomDTO class looks like:
public class HotelRoomDTO
{
public int Id { get; set; }
public string Name { get; set; }
}
And Service is
public async Task<IEnumerable<HotelRoomDTO>> GetHotelRooms(string checkInDate, string checkOutDate)
{
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
var response = await _client.GetAsync($"api/hotelroom?checkInDate={checkInDate}& checkOutDate={checkOutDate}");
var content = await response.Content.ReadAsStringAsync();
var rooms = JsonConvert.DeserializeObject<IEnumerable<HotelRoomDTO>>(content, settings);
return rooms;
}
When i try to run app deserializator crash and doesnt return result. I think that problem is in this "Result" list of objects.When it doesnt exist everithing works fine but when i get data from real Db and try to deserialize it automatic adds this "Result" and code doesnt work
You can try a creting a Root class:
public class Root
{
[JsonProperty("Result")]
public List<HotelRoomDTO> Result { get; set; }
}
And deserialize him:
var rooms = JsonConvert.DeserializeObject<Root>(jsonString, settings);
Your problem is that you are receiving a list of "HotelRoomDTOs", but your model is only made for one.
Diego's answer would work on this occasion. What you want to do is the following. Change your model file to the following:
public class Result
{
public int Id { get; set; }
public string Name { get; set; }
}
public class HotelRoomDTO
{
public List<Result> Result { get; set; }
}
In your GetHotelRooms function you now change
var rooms = JsonConvert.DeserializeObject<IEnumerable<HotelRoomDTO>>(content, settings);
to
var rooms = JsonConvert.DeserializeObject<HotelRoomDTO>(content, settings);
The variable rooms is now a list filled with HotelRoomDTOs.
I found simplest solution i removed "Result" because i dont need it and after that desialize.Thank you for another answers.
var result = JObject.Parse(content)["Result"].ToString(Formatting.None);
var rooms = JsonConvert.DeserializeObject<IEnumerable<HotelRoomDTO>>(content);

Json convert to object error when deserialize object

I convert json to object and get this error
Newtonsoft.Json.JsonSerializationException: 'Error converting value "{"mid":"2","phone":"0965403801","requestId":"1585970510.732827","bankHubToken":"eyJ0aW1lc3RhbXAiOiIxNjMzNDE4NzgyNzQ0IiwidG9rZW4iOiI5NWJmYWM3OC00YmY3LTQyM2MtYjAxNS00NTNjMjkzYzk1ZWEiLCJzaWduIjoiLzVrcTg2dWdReFUvQ1daWCt2TERSaGhvaXN1VC9hS1JpejEwUGtTU0dxUVx1MDAzZCJ9","userName":"1392H46"}" to type 'OBBE.DGBIZ.API.Model.DataFieldUploadFile'. Path '', line 1, position 305.'
my code
var data = context.ActionArguments["data"];
if (data == null)
{
context.Result = new OkObjectResult(
new ErrorResponseMessage() { context = new ContextResponse(false, new List<string>() { APPID, HANDER_ERRORCODE.ERR_REQUEST_CONTENT.ToString(), "Request null" }, new ContextRequest("", ""), ResultConstants.ERROR_CODE_FAIL, "Request null") });
return;
}
try
{
String x = JsonConvert.SerializeObject(data);
data = JsonConvert.DeserializeObject<DataFieldUploadFile>(JsonConvert.SerializeObject(data));
}
and my class
public class DataFieldUploadFile
{
public String? mid { get; set; }
public String? requestId { get; set; }
public String? phone { get; set; }
public String? bankHubToken { get; set; }
public String? userName { get; set; }
}
I try but not OK.
try this
DataFieldUploadFile data = context.ActionArguments["data"] as DataFieldUploadFile;
if data is null it means that data is a probably a json string already, and try to double serialize it.
So you really need this code
string json = context.ActionArguments["data"]?.ToString();
if (!string.IsNullOrEmpty(json))
{
var data = JsonConvert.DeserializeObject<DataFieldUploadFile>(json);
}
else ... you another code

Load JSON object into array?

I'm having trouble loading this json object into an array.
Here is a snippet (fragment) of my JSON response from the API:
{
"count":192,
"value":[
{
"id":"03dd9f56-108f-4e8f-b92e-93df05717464",
"name":"IIBTest",
"url":"https://devops.com/tfs/DefaultCollection/_apis/projects/03dd9f56-108f-4e8f-b92e-93df05717464",
"state":"wellFormed",
"revision":14434848,
"visibility":"private",
"lastUpdateTime":"2016-08-19T12:21:37.187Z"
},
{
"id":"b7e15034-fc8f-4f7e-866a-cb06f44b12ed",
"name":"MS Project POC",
"description":"POC for MS Project with TFS",
"url":"https://devops.com/tfs/DefaultCollection/_apis/projects/b7e15034-fc8f-4f7e-866a-cb06f44b12ed",
"state":"wellFormed",
"revision":14434955,
"visibility":"private",
"lastUpdateTime":"2017-10-03T19:31:56.56Z"
},
{
"id":"59e06621-c5f5-4fd1-9c55-1def541b99d9",
"name":"WorkflowReporting",
"url":"https://devops.com/tfs/DefaultCollection/_apis/projects/59e06621-c5f5-4fd1-9c55-1def541b99d9",
"state":"wellFormed",
"revision":14434591,
"visibility":"private",
"lastUpdateTime":"2015-09-11T06:59:12.21Z"
},
{
"id":"78a802f0-5eee-4bcb-bde9-a764e46f56db",
"name":"iSolutions",
"description":"",
"url":"https://devops.com/tfs/DefaultCollection/_apis/projects/78a802f0-5eee-4bcb-bde9-a764e46f56db",
"state":"wellFormed",
"revision":14435476,
"visibility":"private",
"lastUpdateTime":"2021-08-05T17:17:26.193Z"
},
{
"id":"1f20506a-63a5-486a-a857-fec64d7486a6",
"name":"Training",
"description":"MLITS Training and Learning",
"url":"https://devops.com/tfs/DefaultCollection/_apis/projects/1f20506a-63a5-486a-a857-fec64d7486a6",
"state":"wellFormed",
"revision":14435350,
"visibility":"private",
"lastUpdateTime":"2021-04-08T22:48:02.923Z"
},
...
}
And here is my code:
public class Rootobject
{
public int count { get; set; }
public Value[] value { get; set; }
}
public class Value
{
public string id { get; set; }
public string name { get; set; }
public string url { get; set; }
public string state { get; set; }
public int revision { get; set; }
public string visibility { get; set; }
public DateTime lastUpdateTime { get; set; }
public string description { get; set; }
}
static void Main(string[] args)
{
var client = new RestClient("https://devops.americannational.com/tfs/defaultcollection/_apis/projects?$top=300&api-version=5.0")
{
Authenticator = new RestSharp.Authenticators.NtlmAuthenticator()
};
client.Timeout = -1;
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
var jsonString = response.Content;
var jo = JObject.Parse(jsonString);
//...
}
I am wanting to load the names of the projects into the Array so that I can later iterate through them. Any help is appreciated, I have tried a few things but not having much luck.
you can use var jo = JsonConvert.DeserializeObject<Rootobject>(jsonString);
and then iterate through jo.value
try this
var jsonDeserialized= JsonConvert.DeserializeObject<Rootobject>(json);
as example how to use it this query returns array of project names
var projectNames= jsonDeserialized.value.Select(v => v.name ).ToArray();
output
["IIBTest","MS Project POC","WorkflowReporting","iSolutions","Training"]
this returns a list of projects
var projects= jsonDeserialized.value.ToList();

How to assign value to variable from a google API Json Response c#

I am trying to assign the value of a key from an async JSON response to a variable, the JSON key in question is the "threatType" Key. I am querying google's safebrowsing v4 API and I get a good response, the problem is when I try to assign a key to a variable nothing is assigned. Here's my code:
public static async Task<string> CheckUrl( string Api_Key, string MyUrl)
{
safeBrowsing_panel i = new safeBrowsing_panel();
var service = new SafebrowsingService(new BaseClientService.Initializer
{
ApplicationName = "Link-checker",
ApiKey = Api_Key
});
var request = service.ThreatMatches.Find(new FindThreatMatchesRequest()
{
Client = new ClientInfo
{
ClientId = "Link-checker",
ClientVersion = "1.5.2"
},
ThreatInfo = new ThreatInfo()
{
ThreatTypes = new List<string> { "SOCIAL_ENGINEERING", "MALWARE" },
PlatformTypes = new List<string> { "ANY_PLATFORM" },
ThreatEntryTypes = new List<string> { "URL" },
ThreatEntries = new List<ThreatEntry>
{
new ThreatEntry
{
Url = MyUrl
}
}
}
});
var response = await request.ExecuteAsync();
string json = JsonConvert.SerializeObject(await request.ExecuteAsync());
string jsonFormatted = JToken.Parse(json).ToString(Formatting.Indented);
Console.WriteLine(jsonFormatted);
return jsonFormatted;
}
I created classes to parse the json:
public class ThreatRes
{
public string threatType;
}
public class RootObjSB
{
public List<ThreatRes> matches;
}
And I call it with:
string SB_Result = await CheckUrl("MyAPIKey", "Bad_URL");
RootObjSB obj = JsonConvert.DeserializeObject<RootObjSB>(SB_Result);
The JSON response from google:
{
"matches": [
{
"cacheDuration": "300s",
"platformType": "ANY_PLATFORM",
"threat": {
"digest": null,
"hash": null,
"url": "http://badurl.com/",
"ETag": null
},
"threatEntryMetadata": null,
"threatEntryType": "URL",
"threatType": "SOCIAL_ENGINEERING",
"ETag": null
}
],
"ETag": null
}
I need help please.
So I tried using JavaScriptSerializer and it seemed to work just fine, I also reconstructed my classes to parse all the properties on the JSON response.
Reconstructed Classes:
public class Threat
{
public object digest { get; set; }
public object hash { get; set; }
public string url { get; set; }
public object ETag { get; set; }
}
public class Match
{
public string cacheDuration { get; set; }
public string platformType { get; set; }
public Threat threat { get; set; }
public object threatEntryMetadata { get; set; }
public string threatEntryType { get; set; }
public string threatType { get; set; }
public object ETag { get; set; }
}
public class RootObjSB
{
public List<Match> matches { get; set; }
public object ETag { get; set; }
}
and i deserialize it like this:
string SB_Result = await CheckUrl("MyAPIKey", "Bad_URL");
var obj = new JavaScriptSerializer().Deserialize<RootObjSB>(SB_Result);
string threat = obj.matches[0].threatType;
Console.WriteLine(threat);
I really don't know why the first option I tried didn't parse the data correctly but this was how I overcame that problem. Hope it helps anyone going through the same thing

Newtonsoft JSON deserialize using HttpWebResponse

I was searching in all the questions about deserialization with Newtonsfot Json Converter. But i wasn't able to find the problem in my code. So I put here, asking for help.
The message error from the visual studio:
No se controló Newtonsoft.Json.JsonSerializationException
HResult=-2146233088
Message=Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'APIEffilogics.Usuari+Client' because the type requires a
JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a
type that implements a collection interface (e.g. ICollection, IList)
like List that can be deserialized from a JSON array.
JsonArrayAttribute can also be added to the type to force it to
deserialize from a JSON array.
My JSON response is like this:
[ {
"id": 32,
"consultancy_id": 1,
"nif": "B61053922",
"contactname": "",
"email": "",
"phone": "",
"active": true,
"description": "Keylab" },
{
"id": 19,
"consultancy_id": 1,
"nif": "P0818300F",
"contactname": "Pau Lloret",
"email": "lloret#citcea.upc.edu",
"phone": "",
"active": true,
"description": "Rubi" } ]
And those are the classes:
namespace APIEffilogics
{
public class Usuari
{
public string access_token; //Encapsulat que conté la identificació de seguretat
public string token_type; //Tipus de token, "Bearer"
public string response; //Resposta de l'API
public class Client : Usuari //Estructura client
{
[JsonProperty("id")]
public string cid { get; set; }
[JsonProperty("consultancy_id")]
public string consultancy_id { get; set; }
[JsonProperty("contactname")]
public string contactname { get; set; }
[JsonProperty("email")]
public string email { get; set; }
[JsonProperty("description")]
public string description { get; set; }
[JsonProperty("nif")]
public string nif { get; set; }
[JsonProperty("phone")]
public string phone { get; set; }
[JsonProperty("active")]
public string active { get; set; }
}
public class Building : Usuari //Estructura edifici
{
public string descrip;
public string bid;
}
public class Floor : Usuari //Estructura planta
{
public string descrip;
public string fid;
}
public class Room : Usuari //Estructura habitació
{
public string descrip;
public string rid;
}
public class Node : Usuari //Estructura nodes
{
public string[] descrip;
public string[] nid;
public string[] model;
public string[] type;
}
}
//************************END PUBLIC CLASS Usuari***************************//
}
The code that I use:
public void Request(string url, string metode)
{
try
{
//Enviem la petició a la URL especificada i configurem el tipus de connexió
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
myReq.KeepAlive = true;
myReq.Headers.Set("Cache-Control", "no-store");
myReq.Headers.Set("Pragma", "no-cache");
myReq.Headers.Set("Authorization", usuari.token_type + " " + usuari.access_token);
if (metode.Equals("GET") || metode.Equals("POST"))
{
myReq.Method = metode; // Set the Method property of the request to POST or GET.
if (body == true)
{
// add request body with chat search filters
List<paramet> p = new List<paramet>();
paramet p1 = new paramet();
p1.value = "1";
string jsonBody = JsonConvert.SerializeObject(p1);
var requestBody = Encoding.UTF8.GetBytes(jsonBody);
myReq.ContentLength = requestBody.Length;
myReq.ContentType = "application/json";
using (var stream = myReq.GetRequestStream())
{
stream.Write(requestBody, 0, requestBody.Length);
}
body = false;
}
}
else throw new Exception("Invalid Method Type");
//Obtenim la resposta del servidor
HttpWebResponse myResponse = (HttpWebResponse)myReq.GetResponse();
Stream rebut = myResponse.GetResponseStream();
StreamReader readStream = new StreamReader(rebut, Encoding.UTF8); // Pipes the stream to a higher level stream reader with the required encoding format.
string info = readStream.ReadToEnd();
var jsondata = JsonConvert.DeserializeObject<Usuari.Client>(info);
myResponse.Close();
readStream.Close();*/
}
catch (WebException ex)
{
// same as normal response, get error response
var errorResponse = (HttpWebResponse)ex.Response;
string errorResponseJson;
var statusCode = errorResponse.StatusCode;
var errorIdFromHeader = errorResponse.GetResponseHeader("Error-Id");
using (var responseStream = new StreamReader(errorResponse.GetResponseStream()))
{
errorResponseJson = responseStream.ReadToEnd();
}
}
}
I don't know where is the problem, the response have the correct JSON scheme. Somebody can explain me where is the problem in my code, or if I'm not doing correctly.
I've solved the problem how you say, nut now I've a similar problem and the same message error. The JSON response now is this:
{
nodes: [
{
id: 5,
global_id: 5,
description: "Oven",
room_id: 2,
floor_id: 1,
building_id: 1,
client_id: 2,
nodemodel_id: 2,
nodetype_id: 1
},
{
id: 39,
global_id: 39,
description: "Fridge",
room_id: 2,
floor_id: 1,
building_id: 1,
client_id: 2,
nodemodel_id: 8,
nodetype_id: 1
}, ...
],
limit: 10,
offset: 0
}
And those are the classes:
public class Node : Usuari //Estructura nodes
{
[JsonProperty("limit")]
public int limit { get; set; }
[JsonProperty("offset")]
public int offset { get; set; }
[JsonProperty("nodes")]
public List<Node_sub> nodes_sub { get; set; }
}
public class Node_sub : Node
{
[JsonProperty("id")]
public string nid { get; set; }
[JsonProperty("global_id")]
public string gid { get; set; }
[JsonProperty("description")]
public string descrip { get; set; }
[JsonProperty("room_id")]
public string rid { get; set; }
[JsonProperty("floor_id")]
public string fid { get; set; }
[JsonProperty("client_id")]
public string cid { get; set; }
[JsonProperty("building_id")]
public string bid { get; set; }
[JsonProperty("nodemodel_id")]
public string model { get; set; }
[JsonProperty("nodetype_id")]
public string type { get; set; }
}
The code is the same as before, only I add this sentences:
jsonnode = JsonConvert.DeserializeObject<List<Usuari.Node>>(info);
Why I'm having the same error? List<Usuari.Node> is an array that contains all the items of JSON message.
Thanks
Try
var jsondata = JsonConvert.DeserializeObject<List<Usuari.Client>>(info);
This addresses the issue as the exception suggests:
To fix this error either change the JSON to a JSON object (e.g.
{"name":"value"}) or change the deserialized type to an array or a
type that implements a collection interface (e.g. ICollection, IList)
like List that can be deserialized from a JSON array
Emphasis added to highlight the salient point
The HTTP response you receive is an array of objects so you need to deserialise it in a way that can deal with an array of objects. By changing your code to deserialise into a List<Usari.Client> you do just that and it should resolve the error.

Categories