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
Related
I need to access the body of a JSON Code with C#. Accessing the header works but it does not work with the body and I could not find anything in the web.
I have this JSON Code
`{
"Example": {
"Header": [
[
"Header1",
"Header2",
"Header3",
"Header4"
]
],
"Body": [
{
"Header1": "BlaBla",
"Header2": 0,
"Header3": 20,
"Header4": 32
},
{
"Header1": "BlaBlaBla",
"Header2": 22,
"Header3": 35,
"Header4": 25
},
......`
However I can acess the headers with following code:
JArray headers = locationsObject["Header"] as JArray;
JArray header = headers.Last as JArray; //Last Header
If I do the same with the body it is null:
JArray bodys = locationsObject["Body"] as JArray; //all bodys -> it works here
JArray body = bodys.First as JArray; //First body -> this one is null!!!
I need the integers in the body. I am using Newtonsoft for that. Can someone help me please? Thank you very much!
your first body is not a JArray that could be the source of the problem, it is rather a JObject, you can try the following code, it should work fine
var bodys = locationsObject["Body"] as JArray;
var body = bodys[0];
you can use also linq-to-json for more fine-tuned operations.
I recommend you to look at serializing/deserializing json in c#.
How to serialize and deserialize (marshal and unmarshal) JSON in .NET
If you do not have a class representation of the json json to c#
Your main line of code will be something like this:
exObj = JsonSerializer.Deserialize<ExampleObject>(jsonString);
And it will be:
string header1 = exObj.Body.Header1;
One way of doing this is by using the 'dynamic' variable type of C# which was specifically designed for functional programming languages. It is not type safe and not strong typed but you can access all the values in the result.
I would however strongly recommend you create classes that mimic the json you are trying to deserialize for it will give you strong typing and intellisense.
Here's an example how you can use dynamic. You need to install the NewtonSoft.Json Nuget package for this to function correctly.
using Newtonsoft.Json;
using System;
namespace JsonDeserialized
{
class Program
{
static void Main(string[] args)
{
string json = #"{
'Example':
{ 'Header':
[
[
'Header1',
'Header2',
'Header3',
'Header4'
]
],
'Body':
[
{
'Header1': 'BlaBla',
'Header2': 0,
'Header3': 20,
'Header4': 32
},
{
'Header1': 'BlaBlaBla',
'Header2': 22,
'Header3': 35,
'Header4': 25
}
]
}
}";
var result = JsonConvert.DeserializeObject<dynamic>(json);
Console.WriteLine(result.Example);
foreach (var header in result.Example.Header[0])
{
Console.WriteLine(header);
}
Console.WriteLine(result.Example.Header[0][0]);
}
}
}
This program will print the following result.
{
"Header": [
[
"Header1",
"Header2",
"Header3",
"Header4"
]
],
"Body": [
{
"Header1": "BlaBla",
"Header2": 0,
"Header3": 20,
"Header4": 32
},
{
"Header1": "BlaBlaBla",
"Header2": 22,
"Header3": 35,
"Header4": 25
}
]
}
Header1
Header2
Header3
Header4
Header1
I have a json string like this:
[{
"_id": "abcd",
"name": "bender rodriguez",
"meta": {
"location": {}
},
dob": ,
}
]
The section after dob blows up:
return new JavaScriptSerializer().Deserialize<T>(json);
The problem is the empty dob. I cannot seem to find any method to handle something like this. Doesn't even seem to be a common problem? I'm not too familiar with deserializing json, what methods can I use to deal with this other than string.replace(": ,"," : null,")?
The JSON deserialiser you're using is fine, the JSON you're trying to deserialice is wrong, it's missing a value, and the initial double quotes for the dob property.
Use JSONLint to validate JSON.
If that JSON is coming from a component you control, then use a JSON serializer to serialize it properly, if not, you can fix that particular problem using this:
string myJson = "[{ \"_id\": \"abcd\", \"name\": \"bender rodriguez\", \"meta\": { \"location\": {} }, dob\": , } ]";
JavaScriptSerializer().Deserialize(myJson.Replace("dob\": ", "\"dob\": \"\""));
But if the data changes and it keeps having an invalid JSON format, there's little you can do about it but asking whoever did that component to send you valid JSON data.
Lets say I get the following json data from a web service which I can't change.
[
[
"Header1",
"Header2",
"Header3",
"Header4"
],
[
"FirstValue1",
"FirstValue2",
"FirstValue3",
"FirstValue4"
],
[
"SecondValue1",
"SecondValue2",
"SecondValue3",
"SecondValue4"
]
]
jsonlint.com tells me that it is valid json and from what I know I would agree.
But somehow I'm wondering is there any "easy" way to deserialize this to a class. Each of the values in the second and third array belongs to the corresponding header in the first array.
I know how to use Json.NET but can't get my head around on how to use it with this data structure.
Simple - you can use JsonConvert.DeserializeObject to deserialize it to a string[][]:
using System;
using System.IO;
using Newtonsoft.Json;
class Test
{
static void Main()
{
var json = File.ReadAllText("test.json");
string[][] array = JsonConvert.DeserializeObject<string[][]>(json);
Console.WriteLine(array[1][3]); // FirstValue4
}
}
The easiest way is to use the string class and deserialzie it using Json.NET.
string[][] values = JsonConvert.DeserializeObject<string[][]>(json);
A better option could be to use
using Newtonsoft.Json.Linq
string json = #"{
CPU: 'Intel',
Drives: [
'DVD read/writer',
'500 gigabyte hard drive'
]
}";
JObject o = JObject.Parse(json);
string CPU = o.CPU;
int NumDrives = o.Drives.Count;
Source: http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_Parse.htm
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.
I have a following JSON repsonse from a API.
"{\"status\":\"True\", \"itemID\":\"201\"}".
On client side, how do I get values from status and itemID.
I am NOT working in javascript. This is a c# class.
Use library to work with json. For example, JSON.NET
Here is example:
string json = #"{
""Name"": ""Apple"",
""Expiry"": new Date(1230422400000),
""Price"": 3.99,
""Sizes"": [
""Small"",
""Medium"",
""Large""
]
}";
JObject o = JObject.Parse(json);
string name = (string)o["Name"];
// Apple
JArray sizes = (JArray)o["Sizes"];
string smallest = (string)sizes[0];
// Small
Take a look at this nifty C# 4.0 implementation http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx