How to parse my Json Response String in C# [duplicate] - c#

This question already has answers here:
Parse Json string in C#
(5 answers)
Closed 6 years ago.
This is the JSON Response I'm getting,I unable to parse,Please help me.
{
"features": [{
"attributes": {
"OBJECTID": 1,
"schcd": "29030300431",
"schnm": "UNAIDED GENITALIA LIPS DALMATIA RS"
},
"geometry": {
"x": 8449476.63052563,
"y": 1845072.4204768054
}
}]
}

To parse a JSON you will most likely need a extern library like JSON.Net or something similar.
Then you need to create a classes (a wrapper) with properties that match your JSON String and deserialize the string into that object.
When you create the wrapper class into which you want to deserialize your JSON String you have be careful to name the properties the same way they are named in the JSON String.
Example:
public class MyObject {
public List <Feature> Features {get;set;}
}
public class Feature {
public MyAttributes Attributes {get;set; }
public Geometries Geometries {get;set; }
}
public class MyAttributes {
public int ObjectID {get;set;}
public string Schcd {get;set;}
public string Schnm {get;set;}
}
public class Geometries {
public double X {get;set;}
public double Y {get;set;}
}
Then just call the deserialisation function of the JSON library:
var myObject = JsonConvert.DeserializeObject<MyObject>(jsonString);
To access a property like the Object ID then you just call:
myObject.Features[0].Attributes.ObjectId;

If you're ok with using dynamic you can do like this
var json = "{ \"features\" : [ { \"attributes\": { \"OBJECTID\": 1, \"schcd\": \"29030300431\", \"schnm\": \"UNAIDED GENITALIA LIPS DALMATIA RS\" }, \"geometry\": { \"x\": 8449476.63052563, \"y\": 1845072.4204768054 } } ] }";
dynamic obj = JsonConvert.DeserializeObject(json);
var objectId = obj.features[0].attributes.OBJECTID;
It uses Newtonsoft.Json, which can be installed with Nuget from here.
Install-Package Newtonsoft.Json
Be aware that this doesn't do any null-checks, and simply assumes that it's the first object in features that you want. But it's simple and doesn't require you to create any models.
If you want to use a more complete model I would go for the answer provided by Bojan B or j0ey_wh.

Here is an answer that might get you started Deserialize JSON with C#
I like more the solution from NewtonSoft: Newtonsoft JSON Deserialize
You can use their JsonConverter to simply serialize/deserialize objects
Here's a simple example:
You first need classes that match the structure of your JSON:
public class MyCoolClass
{
public IEnumerable<Feature> features {get; set;}
}
public class Feature
{
public Attributes Attributes {get; set;}
public Geometry Geometry {get; set;}
}
public class Attributes
{
public int ObjectId {get; set;}
public string Schcd {get; set;}
public string Schnm {get; set;}
}
public class Geometry
{
public double X {get; set;}
public double Y {get; set;}
}
Then you just use JsonConverter (JSON.Net) like this:
MyCoolClass tmp = JsonConvert.DeserializeObject<MyCoolClass>(jsonStringThatYouGot);

Related

Reading values from dynamic JSON

Something is making my head in,
I have an API that returns me JSON, the JSON can have a slight different format depending on the endpoint is sending it.
Example.
{
"PayLoad": {
"Method1": [
{
"TimeStamp": "2020-06-03T13:25:25",
"Id": 4235411
}
],
"Timestamp": "2020-06-03T13:26:57.1316371+00:00",
"Signature": "113af0a218b0497ff6f160fcd1b13a7b",
"Hookid": "526ed776-2l71-4c2a-b11f-de8cb2057b1c"
}
}
So what I am looking for is to have returned
Method : Method1
TimeStamp: 2020-06-03T13:25:25
id: 4235411
Signature: 113af0a218b0497ff6f160fcd1b13a7b
HookID: 526ed776-2l71-4c2a-b11f-de8cb2057b1c
Can someone please give me an hint?
I've tried a bunch of code examples I've seen, and can't make it work.
Without getting more information it is hard to know exactly what you are asking but I would look at the examples in JSON.net's Linq to JSON documentation:
https://www.newtonsoft.com/json/help/html/LINQtoJSON.htm
https://www.newtonsoft.com/json/help/html/QueryingLINQtoJSON.htm
string json = #"
{
'PayLoad': {
'Method1':
[
{
'TimeStamp': '2020-06-03T13:25:25',
'Id': 4235411
}
],
'Timestamp': '2020-06-03T13:26:57.1316371+00:00',
'Signature': '113af0a218b0497ff6f160fcd1b13a7b',
'Hookid': '526ed776-2l71-4c2a-b11f-de8cb2057b1c'
}
}";
JObject obj = JObject.Parse(json);
string method1_timestamp = (string)obj["PayLoad"]["Method1"][0]["TimeStamp"];
// "2020-06-03T13:25:25"
// Use technique to parse out other values if needed
You can try creating a class compatible with the expected JSON format:
public class Payload
{
public int Id {get; set;}
public Guid HookID {get; set;}
public string Signature {get; set;}
public Method[] Methods {get; set;}
public DateTime TimeStamp {get; set;}
}
public class Method
{
public int Id {get; set;}
public DateTime TimeStamp{get; set;}
}
Than you can parse the JSON data as a Payload object.
Payload payload = JsonConvert.DeserializeObject<Payload>(json);

Is there a way to Serialize Json that contains a field that contains more json as a string to XML

I receive Json-data from an external source. I need to convert the Json messages to XML.
This is relatively simple using the NewtonSoft library:
var placeHolder = $"{{\"Data\": {jsonContent} }} ";
var xmlNode = JsonConvert.DeserializeXmlNode(placeHolder, "Root").OuterXml;
var doc = new XmlDocument();
doc.LoadXml(xmlNode);
There is one little odd thing about the Json that I receive that breaks this entire process.
The Json looks like this:
[
{
"Type": "Application",
"Object": {
"Duration": 2,
"Request": {
"authReference": "..",
"IdEnrolment": {
"username": "test",
"password": "***",
"createNewUser": false
}
},
"Type": "XXX.SomeController",
"Logs": [
],
"Method": "IdEnrolments",
"Response": {
"IdUsername": null,
"result": {
"resultCode": 0,
"resultTitle": null,
"resultMessage": null
}
}
}
},
{
"Type": "Proxy",
"Object": {
"Assembly": null,
"Policy": null,
"Cache": null,
"Duration": 516,
"Request": "{\"AuthenticateUserRequest\":{\"EnterpriseContext\":{\"ContextInfo\":{\"#xmlns\":\"http://example.xom\",\"ProcessContextId\":\"adad\",\"ExecutionContextId\":\"adac\"}\"}}",
"Type": "https://someserver/services/ent/informationandtechnologymanagement/company/v1",
"Logs": [
],
"Method": "AuthenticateUser",
"Response": "{\"AuthenticateUserResponse\":{\"EnterpriseContext\":{\"ContextInfo\":{\"#xmlns\":\"http://example.com\",\"ProcessContextId\":\"adad\",\"ExecutionContextId\":\"adad\"}}}}"
}
}
]
The first object in the array is perfect and serializes correctly. The second object in the array causes chaos (understandably). The Request and Response fields for this object are actually Strings and they contain the JSON code.
Is there a way to deserialize this properly? I realize that it is a lot to ask from a library to be flexible enough to do this - but I'm just a little stumped at how to use this.
All the messages I receive look roughly the same - but specifically the content of the Request and Response objects are different depending on the specific request/response.
The guys who built this do not have any sort of Schema or contract in place, other than the fact that they send Json text around and they seem unwilling or unable to change how the Json is created.
Any advice will really be appreciated.
Note: It seems that the behavior isn't random. Whether I get a proper object or a string is determined by the attribute: "Type": "Application". There are many different "Types" - and some are properly serialized and others not.... Aaarrggghhh!!!! Frustration !!!!
Your JSON is bricked in root/Type:Proxy/Object/ the Request-nesting is malformed:
"Request": "{\"AuthenticateUserRequest\":{\"EnterpriseContext\":{\"ContextInfo\":{\"#xmlns\":\"http://example.xom\",\"ProcessContextId\":\"adad\",\"ExecutionContextId\":\"adac\"}\"}}",
Here you have 4 curly brackets open, but only 3 that close.
The JSON you have to handle is very very irregular and bad, so that you just have to deconstuct all of that into C# interfaces, classes, and structs like so:
#region Fields
enum JsonObjType
{
Application,
Proxy,
SomeController,
}
#endregion
#region Classes
// Application
public class AppObj : JsonObjMaster
{
public readonly JsonObjType Type_Ind {get;}
public int Duration {get; set;}
public AppRequest Request {get; set;}
public AppObjController Controller {get; set;}
//you need a default constuctor for classes, cause else no json parser will work with them
public AppObj()
{
Type_Ind = JsonObjType.Application;
Duration = 0;
AppResult = String.Empty;
Request = new AppRequest();
Controller = new AppObjController();
}
}
public class AppObjController : JsonObjSlave
{
public readonly JsonObjType Type_Ind {get;}
public string[] Logs {get; set;}
public Func</*whatever is supposed to be here*/> Method {get; set;}
public AppResult Result {get; set;}
public AppObjController()
{
Type_Ind = JsonObjType.SomeController;
Log = Array.Empty<string>();
Method = (/*whatever is supposed to be here*/) => null; //may need to change depending on what the function is for
Result = new AppResult();
}
}
// Proxy
public class ProxyObj : JsonObjMaster
{
public readonly JsonObjType Type_Ind {get;}
public int Duration {get; set;}
public string Assembly {get; set;} //I am assuming strings here since no type is supplied
public string Policy {get; set;}
public string Cache {get; set;}
public string Request {get; set;}
public string Type {get; set;}
public string[] Logs {get; set;}
public Func</*whatever is supposed to be here*/> Method {get; set}
public string Response {get; set;}
public ProxyObj()
{
Type_Ind = JsonObjType.Proxy;
Duration = 0; //not needed but to stay consistent
Assembly = String.Empty();
Policy = String.Empty();
Cache = String.Empty();
Request = String.Empty();
Type = String.Empty();
Logs = Array.Empty<string>();
Method = (/*whatever is supposed to be here*/) => null; //may need to change depending on what the function is for
Response = String.Empty();
}
}
#endregion
#region Structs
// Interfaces
public interface JsonObjMaster
{
public readonly JsonObjType Type_Ind {get;}
public int Duration {get; set;}
}
public interface JsonObjSlave
{
public readonly JsonObjType Type_Ind {get;}
}
// Structs
public struct IdEnrolment
{
public string Username {get; set;}
public string Password {get; set;}
public bool CreateNewUser {get; set;}
}
public struct AppResult
{
public int Code {get; set;}
public string Title {get; set;}
public string Message {get; set;}
}
public struct AppRequest
{
public string AuthRefernece {get; set;}
public IdEnrolment {get; set;}
}
#endregion
In order to load the JSON into the classes you now need to supply the parer with the names of the C# object properties in the context of the JSON file so that the parser can link them. This can look something like this:
[MyJsonparser.JsonName("Type")]
public string Type {get; set;}
But it is highly dependant on the JSON lib you're using, so you need to look it up in their docs.
If you can sucsessfully convert the JSON fuckery that someone (hopefully not you) did into C# objects you can then resolve the JSON strings that are left over by moving to another layer of classes and structs, which you can then use for processing.
Now after you have that JSON as C# ocjects you can easily serialize it to XML but sadly because of how bad the JSON is implemented you wont be able to do it automatically without using C# objects as a meta-medium.

C# get children from JSON

my JSON looks like this:
{
"kind": "youtube#videoListResponse",
"etag": "\"sZ5p5Mo8dPpfIzLYQBF8QIQJym0/TOPzMxlQJUtRJBXHeKYMXsdEkHs\"",
"pageInfo":
{
"totalResults": 1,
"resultsPerPage": 1
},
"items":
[
{
"kind": "youtube#video",
"etag": "\"sZ5p5Mo8dPpfIzLYQBF8QIQJym0/BIVqr1Mkbule8othzWvZRor92wU\"",
"id": "QMNkWwq6L4Q",
"contentDetails":
{
"duration": "PT4M45S",
"dimension": "2d",
"definition": "hd",
"caption": "false",
"licensedContent": true,
"projection": "rectangular"
}
}
]
}
The formatting might be a bit off, sorry.
I tried creating a class like this:
public class VideoDetails
{
public string kind;
public string etag;
public string id;
public string duration;
public string definition;
public string caption;
public string licensedContent;
public string projection;
}
After that I deserialize the JSON file:
VideoDetailRead = JsonConvert.DeserializeObject<VideoDetails>(json);
but I only get "etag" and "kind". Nothing else. My question is: How do I read the data that's listed under "items"? This is my first time working with JSON and therefor I don't know much. Thanks for some answers.
Create a second object to model the children data. Provided the items property has also a child under contentDetails, you will also need another object to deserialize these properties.
public class VideoDetailsItem
{
public string kind;
public string etag;
public string id;
public VideoContentDetails contentDetails;
}
public class VideoContentDetails
{
public string duration;
public string definition;
public string caption;
public bool licensedContent;
public string projection;
}
And to the parent object add a List<VideoDetailsItem>.
public class VideoDetails
{
public string kind;
public string etag;
public List<VideoDetailsItem> items;
}
When deserializing JSON objects you have to mimic the JSON object structure in your object. Also, consider using properties instead of public fields to favor encapsulation in your data objects.
The properties you have listed are inside an array named items, so your object hierarchy has to match this:
public class VideoList
{
public string kind;
public string etag;
// etc...
public List<VideoDetails> items;
}
public class VideoDetails
{
public string kind;
public string etag;
public string id;
public string duration;
public string definition;
public string caption;
public string licensedContent;
public string projection;
}
Then:
var videos = JsonConvert.DeserializeObject<VideoList>(json);
This is because you aren't properly modeling the object structure. Right now, your JSON is structured like:
{baseInformation, VideoDetailsArray}
Thus you have to restructure your data object as
public class VideoDetails
{
//Base information
public string kind {get; set;}
public string etag {get; set;}
//...
public List<VideoDetails> {get; set;}
}
You have to define your class to match the structure of the JSON: in this case, you would define items as a list of a separate class which has the properties under it like duration etc. You should have your VideoDetails class nested inside another class that can wrap both objects in the JSON, and add another class for the contentDetails object.
One thing you can do is copy the JSON into your clipboard, open a new class file in Visual Studio, and go to Edit > Paste Special > Paste JSON as Classes. This will create the correct structure for you, and you can see how the nested classes in the JSON properly translate to C# classes.

Creating a class for de/serializing

I have a JSON string like:
var json = "{\"Attributes\": {\"name\":\"S1\", \"quantity\":\"100\"}}";
I want to design a class for the same; how does one approach while creating a class for JSON string in C# ?
If you are using Visual Studio 2012, go in the menu to EDIT -> Paste Special -> Paste JSON As CLasses.
You valid JSON should probably look like this (you should remove the \ before copying it to the clipboard):
{"Attributes": {"name":"S1", "quantity":"100"}}
The generated classes:
public class Rootobject
{
public Attributes Attributes { get; set; }
}
public class Attributes
{
public string name { get; set; }
public string quantity { get; set; }
}
Sample usage (note that the \ is still here, in order to have valid code syntax):
var json = "{\"Attributes\": {\"name\":\"S1\", \"quantity\":\"100\"}}";
var json_serializer = new JavaScriptSerializer();
Rootobject dc = json_serializer.Deserialize<Rootobject>(json);
You're question's unclear, but I assume you mean parsing JSON in to C# objects? Using JSON.NET and something like this can do that:
public class Attributes
{
[JsonProperty("name")]
public String Name { get; set; }
[JsonProperty("quantity")]
public Int32 Quantity { get; set; }
}
public class MyObject
{
[JsonProperty("Attributes")]
public Attributes Attributes { get; set; }
}
var myObj = JsonConvert.DeserializeObject<MyObject>(json);
Or you can go more broadly and let JSON.NET do it for you:
var obj = JsonConvert.DeserializeObject<dynamic>(
"{ \"Attributes\": {\"name\":\"S1\", \"quantity\":\"100\"}}"
);
Console.WriteLine(obj.Attributes["name"]) // S1
Console.WriteLine(obj.Attributes["quantity"]) // 100
have a look at the namespace System.Runtime.Serialization, you can find useful classes for (de)serializing JSON there
also you can read this similar question (searching before posting does not really hurt):
How do I represent this complex json document as a C# object?

JSON.NET DeserializeObject from array by order to a list

I am trying to Deserialize a Json Object into Dynamic List by order, so I have:
Json:
string json = "{'elements':[
{'EntityA':[
{'name ':'Jhon'}
],
'EntityB':[
{'title' : 'car'}
],
'EntityB':[
{'title':'aaa'}
],
'EntityA':[
{'name' : 'Alice'}
]]}";
.NET Classes Base Classes:
public interface EntitysInterface{}
public class EntityA: EntitysInterface
{
public string name { get; set; }
}
public class EntityB: EntitysInterface
{
public string title { get; set; }
}
public class Entitys
{
public List<EntitysInterface> elements { get; set; } //EntityA, EntityB,...
public Entitys()
{
}
}
My DeserializeObject Dificult:
Entitys listFinaly = JsonConvert.DeserializeObject<Entitys>(json);
Exception "Type is an interface or abstract class and cannot be instantiated. :( "
The JSON.NET deserializer is telling you that it can't figure out which EntitysInterface object that you would like selected. It requires that you give it a hint.
ContractResolver helps to give that hint.
This post answers a similar question.
EDIT:
There is a good example in the JSON.Net documentation.

Categories