Class Object with Dynamic Structure - c#

Hi Am trying to parse a json Object with Help of C# DataContractJsonSerializer And this is what json may look like
{"user_id":"121","Q1":"question 1","Q2":"question 2","Q3":"question 3"}
And Number of question can be 200- 500,
So I dont want to make a DataContract with 500 Variables to parse this Json, So I was thinking if there is a way where i can call the constructor or something for this class object with a number parameter like this if there are Q1 - Q30 in jSon
Objectparse new_object = new Objectparse(30);
Which will create variables Q1 to Q30 at runtime? and parse the Json

You could use JavaScriptSerializer:
var json = #"{""user_id"":""121"",""Q1"":""question 1"",""Q2"":""question 2"",""Q3"":""question 3""}";
var serializer = new JavaScriptSerializer();
dynamic result = serializer.DeserializeObject(json);
Console.WriteLine(result["Q1"]);
Console.WriteLine(result["Q2"]);
...
and if you are using an older version of .NET than 4.0 and cannot use the dynamic feature you could do this:
var json = #"{""user_id"":""121"",""Q1"":""question 1"",""Q2"":""question 2"",""Q3"":""question 3""}";
var serializer = new JavaScriptSerializer();
var result = (IDictionary<string, object>)serializer.DeserializeObject(json);
Console.WriteLine(result["Q1"]);
Console.WriteLine(result["Q2"]);
...
But let me point out that this is an extremely poor JSON design. The person that designed this class was probably not aware of javascript arrays:
{
"user_id": "121",
"questions": [
{
"key": "Q1",
"value": "question 1"
},
{
"key": "Q2",
"value": "question 2"
},
{
"key": "Q3",
"value": "question 3"
}
]
}
Which could now be serialized into a strongly typed object containing a collections of questions.

Related

How to convert List<model> to string?

I have a list of data and want to convert it into string format like headers and values separated. How can I achieve this in c#?
Expected Result:
dynamic data = {
"values": [
[
5658830,
"Support And Training Services Llc",
"PAM",
"FINNESAND"
],
[
5658831,
"Training Services Llc",
"Bob",
"MCCART"
]
],
"headers": [
"ID",
"ENT_COMPANY1",
"FirstName",
"LastName"
]
}
How to convert in List into above format?
Here's a quick snippet to answer your question, in my own code. You'll still have to propogate the list of objects with whatever it is you have. Just change "object" to the name of your model.
List<string> listOfStrings = new List<string>();
List<object> listOfMyModels = new List<object>();
//fill your list of objects here with whatever it is you're converting to a string
foreach(object myObject in listOfMyModels)
{
string json = JsonConvert.SerializeObject(myObject);
listOfStrings.Add(json);
}
Now you have a list of strings that represent your objects and when needed, you can use the deserialize method to read it.

C# get value from deserialized json object

I'm currently Deserializing a json string using the Newtonsoft.Json nuget packet using the following code:
var data = (JObject)JsonConvert.DeserializeObject(json);
Now I'm receiving an object in the following format:
{{ "meta": { "rap": 2098, "count": 5 }, "data": [ { "name": "Gold Tetramino of Mastery", "rap": 735, "uaid": "16601901", "link": "https://www.roblox.com/Gold-Tetramino-of-Mastery-item?id=5786047", "img": "https://t4.rbxcdn.com/081337d7ea86e6a406512aaa83bbcdeb", "serial": "---", "count": 1 }, { "name": "Silver Tetramino of Accomplishment", "rap": 385, "uaid": "16601900", "link": "https://www.roblox.com/Silver-Tetramino-of-Accomplishment-item?id=5786026", "img": "https://t1.rbxcdn.com/60da69cd76f8dad979326f63f4a5b657", "serial": "---", "count": 1 }, { "name": "Subzero Ski Specs", "rap": 370, "uaid": "155175547", "link": "https://www.roblox.com/Subzero-Ski-Specs-item?id=19644587", "img": "https://t4.rbxcdn.com/8ead2b0418ef418c7650d34103d39b6d", "serial": "---", "count": 1 }, { "name": "Rusty Tetramino of Competence", "rap": 319, "uaid": "16601899", "link": "https://www.roblox.com/Rusty-Tetramino-of-Competence-item?id=5785985", "img": "https://t2.rbxcdn.com/968ad11ee2f4ee0861ae511c419148c8", "serial": "---", "count": 1 }, { "name": "Bluesteel Egg of Genius", "rap": 289, "uaid": "16601902", "link": "https://www.roblox.com/Bluesteel-Egg-of-Genius-item?id=1533893", "img": "https://t7.rbxcdn.com/48bf59fe531dd1ff155e455367e52e73", "serial": "---", "count": 1 } ]}}
Now I'm trying to get the following value from it:
"rap": 2098,
I just need 2098 and I've been trying the following code:
string rap = data["rap"].Value<string>();
But sadly this wouldn't work. Does anyone have a idea how to get the value?
Try:
var result = data["meta"]["rap"].Value<int>();
or
var result = data.SelectToken("meta.rap").ToString();
or if you don't want to want to pass the whole path in, you could just search for the property like this:
var result = data.Descendants()
.OfType<JProperty>()
.FirstOrDefault(x => x.Name == "rap")
?.Value;
Instead of declaring as type var and letting the compiler sort it, declare as a dynamic and using the Parse method.
dynamic data = JArray.Parse(json);
Then try
data.meta.rap
To get the internal rap object.
I edited from using the deserializeobject method as i incorrectly thought that had the dynamic return type. See here on json.net documentation for more details: http://www.newtonsoft.com/json/help/html/QueryJsonDynamic.htm
I just came to add Yet another way to get 2098:
After having got your object in the way you actually did:
var data = (JObject)JsonConvert.DeserializeObject(json);
The first you have to note is that the value you want to get is itself a value of the property "meta":
so, first you have to extract the contents of "meta" by simply calling
data["meta"]
and just then you are able to ask for the Value<string> of "rap":
String rap = data["meta"].Value<string>("rap");
which acctually gives you the value you were looking for:
Console.WriteLine(rap); // 2098
var jobject = (JObject)JsonConvert.DeserializeObject(json);
var jvalue = (JValue)jobject["meta"]["rap"];
Console.WriteLine(jvalue.Value); // 2098
The value is actually an int type. Try:
int rap = data["rap"].Value<int>();
string rap = JsonConvert.DeserializeObject<dynamic>(json).meta.rap;
Console.WriteLine(rap); // 2098
If you're not into dynamic (or aren't using .NET 4+), I like how this other answer relies solely on Json.NET's API.
Try to use as following
var test = JsonConvert.DeserializeObject<dynamic>(param);
var testDTO = new TPRDTO();
testDTO.TPR_ID = test.TPR_ID.Value;
Note: For using of JsonConvert class you have to install Newton-Soft from your package-manager
the problem is that you are casting the deserialized json into a JObject. if you want to have the JObject then simple do this:
JObject.Parse(json);
then you have the JObject and you can access a specific path (for extracting value see this )
you have also another option which is to deserialize your json into a class that you have in your code like this:
var instanceOFTheClass = JsonConvert.DeserializeObject<YourClassName>(json);
with the above code you can access any property and values you want.
Use the enumerator to get at the value:
var data = (JObject)JsonConvert.DeserializeObject(json);
var enumerator = data.GetEnumerator();
enumerator.MoveNext();
var dataValue = enumerator.Current.Value.ToString();
Just use dynamic representation of object:
dynamic obj = JsonConvert.DeserializeObject(json)
var value = obj.meta.rap;
JObject easily convertable to dynamic type itself. You can either get string or int from this value:
var ivalue = (int)obj.meta.rap;
var svalue = (string)obj.meta.rap;

Comparing JSON response of

Good morning everyone. I have a service which returns me a JSON response (something like below):
{
"sessionid": "AQIC5wM2LY4SfcytTIcteNkTtCVrE8A-AS7VR*",
"Customers": [
{
"id": "4193942846",
"firstname": "Anto",
"lastname": "Paul",
"customertype": "ph",
"companyCode": "ABCD",
},
{
"id": "4193942236",
"firstname": "Dimple",
"lastname": "Paul",
"customertype": "ph",
"companyCode": "AB",
}
],
"Status": "ACTIVE",
"serviceStatus": "SUCCESS",
"Addresses": {
"Address": [
{
"type": "M",
"addr1": "11011, main st",
"addr2": "Apt. 2",
"zipcode": "11011"
}
]
}
}
The above structure varies based on the input I pass to the service. So, I cant contruct one class to deserialize the response. I need to compare (attribute-attribute comparison) this response to a response I already have with me (in a different place).
I tried to do it with dynamic class in C# but no luck so far. Could someone share a better,working approach? Thank you.
You can use JToken.DeepEquals like this:
var response = JObject.Parse(responseJson);
var goldenStandard = JObject.Parse(goldenStandardJson);
if (JToken.DeepEquals(response, goldenStandard))
{
// the two JSONs have the same data
}
Try Json.Net. It supports dynamic structures.
Here is a tutorial:
http://www.codeproject.com/Tips/631586/Dynamic-types-with-JSON-NET
Use this:
https://jsonutil.codeplex.com/
var obj1 = JSONSerializer.Deserialize(jsontext1);
var obj2 = JSONSerializer.Deserialize(jsontext2);
bool Compare(object obj1, object obj2)
{
//if(obj1 is JSONObject && obj2 is JSONObject)
// => typecase and use jsonObj1.Members to iterate over members and compare values recursively
//if JSONArray, then iterate over items and compare
//if anything else... i.e. primitive then compare directly
//else return false;
}
If you are using this JSON response one time, then you can use a dynamic JSON NET types.
But if you are using this JSON structure response some times, then it is preferable to make this response to a c# classes (objects), so you will have a very easy access to it's properties, you just have your c# objects and they have properties and you can simply approach to each field you wish (with intellisense). By the way, it is very easy to copy a JSON response to a C# classes (something like copy paste). Here is how to do that:
http://blogs.msdn.com/b/webdev/archive/2012/12/18/paste-json-as-classes-in-asp-net-and-web-tools-2012-2-rc.aspx

Convert Object to Array or list

i have an object that is being passed to me from a json obj, each time it is has different feilds, i am using json.net to parse it, it is parsing it correctly and it is putting it in a list of obj
the format after serialization is:
{
"language": "EN",
"code": "test",
"name": "test",
"value": "TEST",
"id": "2222222222222222"
}
the fields are dynamic it can be up to 50 not just 5
any idea on how to parse it??
If you know the items in above format. you could create an typed object. and then you can use DataContractJsonSerializer like below.
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(List<Student>));
List<Student> result = obj.ReadObject(stream) as List<myClass>;

Deserialize a Dynamic JSON Array on C# WebForm

Hi I am generating a JSON on my API that I am trying to use on codebehind C# in my web application but I cannot deserialize well.
My JSON has an object with JSON arrays and the element inside the array are dynamic so I cannot create a fixed class with those items becuase my JSON can have N ITEMS.
{
"MAINOBJET": [{
"ITEM1": "23800",
"ITEM2": "Dahl; Police",
"ITEM3": "test#test.net"
},
{
"ITEM1": "23802",
"ITEM2": "Steve ; Police",
"ITEM3": "test2#test.net"
}]
}
So how can I deserialize it to a DataTable, list or a Dictionary?
Thank you
here you can do some thing like the following this example should be able to get you started .. replace the structure / example with your Jason Text
lets say that my JSON Script looks like the following
{
"some_number": 253.541,
"date_time": "2012-26-12T11:53:09Z",
"serial_number": "SN8675309"
"more_data": {
"field1": 1.0
"field2": "hello JSON Deserializer"
}
}
assign you JSON jsonText to a variable and pass it to the following C# Code
using System.Web.Script.Serialization;
var jsonSerialization = new JavaScriptSerializer();
var dictObj = jsonSerialization.Deserialize<Dictionary<string,dynamic>>(jsonText);
Console.WriteLine(dictObj["some_number"]); //outputs 253.541
Console.WriteLine(dictObj["more_data"]["field2"]); //outputs hello JSON Deserializer

Categories