Below is the format of post request expected in JSON. Can anyone please tell me how to achieve this.
{
"MywebServiceInputDetail":{
"MyDatalst":{
"MyData":[
{
"name":"TestName",
"id":"2611201",
"SomeRefVal":"REF123456"
}
]
}
}
}
I am using JavaScriptSerializer as of now.
Below is the code.
[Serializable]
public struct MyStruct
{
public string name;
public string id;
public string refno;
}
JavaScriptSerializer jss = new JavaScriptSerializer();
string serializedJson = jss.Serialize(ObjMystrcut);
Above code results in the JSON string as
{"name":"TestName","id":"1234567","refno":"567123"}
I am new to JSON so I'm not able to formulate the request format.
I am avoiding to achieve it by hardcoding a json string. Basically, I am trying to understand what does { and [ bracketing mean. Does [ mean that I need to create an array of objects?
You can do something like this:
string serializedJson = jss.Serialize(new { MywebServiceInputDetail = new { MyDatalst = new { MyData = new[] { ObjMystrcut } } } });
{} is object notation, so it represents an object, with properties.
[] is an array notation.
Yes, the [ and ] symbols represent JSON arrays (collections of objects). In your example, MyData is a collection of those structs you created.
You need to create the following classes:
public class MywebServiceInputDetail
{
public MyDatalst MyDatalst { get; set; }
}
public class MyDatalst
{
public List<MyStruct> MyData { get; set; }
}
public struct MyStruct
{
public string name;
public string id;
public string SomeRefVal;
}
Now create a MywebServiceInputDetail object and serialize it.
Personally I would forget about using a struct and just create the following class instead:
public class MyClass
{
public string Name { get; set; }
public string Id { get; set; }
public string SomeRefVal { get; set; }
}
You should also add JSON attributes to the properties to make sure Name and Id are serialized with lowercase letters.
Related
I've managed to find a solution without removing the paths from the keys.Thanks for the help guys, and also pointing out problems, I really appreciate it! :)
Loaded the Json to a string, deserialized it into a dynamic, ran a foreach through it, and added to a List with ResFiles in it.
static void loadJson()
{
List<ResFile> fileList = new List<ResFile>();
string jsonString = File.ReadAllText(jsonPath);
dynamic files = JsonConvert.DeserializeObject(jsonString);
foreach (var f in files.objects)
fileList.Add(new ResFile(f.Name, f.Value.hash.ToString(), (int)f.Value.size.Value));
}
I'm trying to deserialize some Json file in C# with Newtonsoft's Json library.
The files are named after it's hash, not the real file name and I want to rename them back to the proper names, so like this:
10a54fc66c8f479bb65c8d39c3b62265ac82e742 >> file_1.ext
The Json file:
{
"files": {
"file_1.ext": {
"hash": "10a54fc66c8f479bb65c8d39c3b62265ac82e742",
"size": 8112
},
"file_2.ext": {
"hash": "14cfb2f24e7d91dbc22a2a0e3b880d9829320243",
"size": 7347
},
"file_3.ext": {
"hash": "bf7fadaf64945f6b31c803d086ac6a652aabef9b",
"size": 3838
},
"file_4.ext": {
"hash": "48f7e1bb098abd36b9760cca27b9d4391a23de26",
"size": 6905
}
}
}
I've tried deserialize with this:
static void loadJson()
{
using (StreamReader reader = new StreamReader(jsonPath))
{
string json = reader.ReadToEnd();
dynamic files = JsonConvert.DeserializeObject(json);
}
}
The deserialization itself working, but I don't know how to loop through them.
I've also tried to do this:
class ResFile
{
public string name;
public string hash;
public int size;
}
And somehow force the deserialization to use this, but it didn't work of course.
According to your sample json, your classes would be:
public class ResFile
{
public string hash { set; get; }
public int size { set; get; }
}
public class ResRoot
{
public Dictionary<string, ResFile> Files { set; get; }
}
You can deserialize as
var res = JsonConvert.DeserializeObject<ResRoot>(File.ReadAllText(filename));
foreach(var f in res.Files)
{
Console.WriteLine("Name={0} Size={1}", f.Key, f.Value.size);
}
Please follow the C# conventions and do not expose member variables as public or start property names with lower case. In order to make your conventional objects deserializable, you could use the System.Runtime.Serialization DataContract and DataMember attributes. DataContract indicates that an object of this type is serializable and DataMember is used to specify a property's serialization name.
class ResFile
{
[DataMember(Name = "name")]
public string Name { get; set; }
[DataMember(Name = "hash")]
public string Hash { get; set; }
[DataMember(Name = "size")]
public int Size { get; set; }
public ResFile () { }
}
[DataContract]
class ResFileCollection
{
[DataMember(Name ="files")]
public Dictionary<string, ResFile> Files { get; set; }
}
And here is the deserialization:
string json = File.ReadAllText("data.json");
var files = JsonConvert.DeserializeObject<ResFileCollection>(json);
foreach(KeyValuePair<string, ResFile> f in files.Files)
{
Console.WriteLine("{0} {1} {2}", f.Key, f.Value.Name, f.Value.Hash);
}
Serialized property names should also be shorter for better performance. An example:
[DataMember(Name="src")]
public string SourcePath { get; set; }
I have the following JSON
{
"employee" : {
"property1" : "value1",
"property2" : "value2",
//...
}
}
to a class like
public class employee
{
public string property1{get;set;}
public string property2{get;set;}
//...
}
In my JSON if I need to add property3 then I need to make changes in my class too.
How can I deserialize to a class even though if I change my JSON(adding another property like property3).
The serialize/De-serialize techniques like newtonsoft.json is tightly coupled with the Class.
Is there a better way/tool to deserialize these kind of JSON in portable class in c#?
Newtonsoft is not tightly coupled with strong types. You can deserialize the dynamic types too. See the similar question here (How to read the Json data without knowing the Key value)
You can try .net's JavaScriptSerializer (System.Web.Script.Serialization.JavaScriptSerializer). If some field is added or removed it deserializes object normally.
namespace ConsoleApplication8
{
public class Person
{
public int PersonID { get; set; }
//public string Name { get; set; }
public bool Registered { get; set; }
public string s1 { get; set; }
}
class Program
{
static void Main(string[] args)
{
var s = "{\"PersonID\":1,\"Name\":\"Name1\",\"Registered\":true}";
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var o = serializer.Deserialize<Person>(s);
;
}
}
}
If we can use " Dictionary<string,string> employee" the above json can be deserilized.
I have the following issue with this json :
{
"EVTS": {
"EVT": [
{ "ID": "123456",
"KEY1" : "somekey",
"CATEG": [
"cat1",
"cat2",
"cat3"
]
}
]}
}
and this c# class:
public class myClass{
public string ID { get; set; }
public string KEY1 { get; set; }
public list<string> CATEG { get; set; }
}
public class ESObject1
{
[JsonProperty("EVT")]
public List<myClass> EVT { get; set; }
}
public class ESObject0
{
[JsonProperty("EVTS")]
public ESObject1 EVTS { get; set; }
}
}
here i call the deserializer :
ESObject0 globalobject = JsonConvert.DeserializeObject<ESObject0>(json);
But this last code doesnt work, i throws this exception : System.ArgumentException: Could not cast or convert from System.String to System.Collections.Generic.List1[System.String].`
Instead of list<string> i used string [] and only string nothing seems to work.
how can i deserialize this object correctly please.
Thank you.
There doesn't seem to be any apparent problem wit hyour code as this working example illustrates:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
public class myClass
{
public string ID { get; set; }
public string KEY1 { get; set; }
public List<string> CATEG { get; set; }
}
public class ESObject1
{
[JsonProperty("EVT")]
public List<myClass> EVT { get; set; }
}
public class ESObject0
{
[JsonProperty("EVTS")]
public ESObject1 EVTS { get; set; }
}
class Program
{
static void Main()
{
string json =
#"{
""EVTS"": {
""EVT"": [
{
""ID"": ""123456"",
""KEY1"": ""somekey"",
""CATEG"": [
""cat1"",
""cat2"",
""cat3""
]
}
]
}
}";
ESObject0 globalobject = JsonConvert.DeserializeObject<ESObject0>(json);
foreach (string item in globalobject.EVTS.EVT[0].CATEG)
{
Console.WriteLine(item);
}
}
}
Maybe you just fed a wrong json value to the deserializer which doesn't look like as the one shown in your question. By the way, the one shown i nyour question is invalid JSON as you are missing a , after KEY1 property declaration.
UPDATE:
Now that you have shown your real JSON (coming from http://donnees.ville.quebec.qc.ca/Handler.ashx?id=69&f=JSON) it appears that there's a row where CATEG is not an array of strings but a simple string:
""CATEG"": ""Conférence""
Now that's a pretty bad design because they are mixing arrays and simple properties. I am afraid that in order to deal with this situation you will need to use JObjects and extract the information you need by testing the actual underlying type.
For example:
var obj = JObject.Parse(json);
var events = (JArray)obj["EVTS"]["EVT"];
foreach (JObject evt in events)
{
var categories = evt["CATEG"];
if (categories is JArray)
{
// you've got a list of strings so you can loop through them
string[] cats = ((JArray)categories)
.Select(x => x.Value<string>())
.ToArray();
}
else
{
// you've got a simple string
string cat = categories.Value<string>();
}
}
I have done this many times with many many headaches. My advice is take the json output and use a tool similar to this to write your class for you (http://json2csharp.com/).
Then go over any nullable variables and add nullable type (ex. using int? for int) where needed.
I have a JSON data as follows
{"id": "367501354973","from": {
"name": "Bret Taylor",
"id": "220439" }
which is returned by an object(result) of IDictionary[String, Object]
In my C# code:
I have made a class for storing the JSON value which is as follows
public class SContent
{
public string id { get; set; }
public string from_name { get; set; }
public string from_id { get; set; }
}
My main C# function which stores the parses the JSON data and stores the value inside the class properties is as follows:
List<object> data = (List<object>)result["data"];
foreach (IDictionary<string, object> content in data)
{
SContent s = new SContent();
s.id = (string)content["id"];
s.from_name = (string)content["from.name"];
s.from_id = (string)content["from.id"];
}
When i execute this code, i get an exception saying System cannot find the Key "from.name" and "from.id"
When i comment the two lines (s.from_name = (string)content["from.name"];s.from_id = (string)content["from.id"];) my code runs fine.
I think i am not able to refer the nested JSON data properly.
Can anyone just validate it and please tell me how to refer nested data in JSON in C#?
Thanks
I'm not sure how you are parsing the JSON string. Are you using a class in the Framework to do the deserialization?
You could use the JavaScriptSerializer Class defined in the System.Web.Script.Serialization Namespace (you may need to add a reference to System.Web.dll)
Using that class, you would write your code like this:
public class SContent
{
public string id { get; set; }
public SFrom from { get; set; }
}
public class SFrom
{
public string name { get; set; }
public string id { get; set; }
}
Then deserialization looks like this:
var json = new JavaScriptSerializer();
var result = json.Deserialize<SContent>(/*...json text or stream...*/);
See JavaScriptSerializer on MSDN. You might also want to check out this similar question.
My application is asp.net. I have to send some values back to server. For this I create a object serialize it and send it to server. At server I try to de-serialize it
Following is my code
[Serializable]
public class PassData
{
public PassData()
{
}
public List<testWh> SelectedId { get; set; }
public string SelectedControlClientId { get; set; }
public string GroupTypeId { get; set; }
public string SectionTypeId { get; set; }
}
[Serializable]
public class testWh
{
public testWh()
{
}
public string Id { get; set; }
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
//this can not serialize the SelectedId and the count remains 0
PassData data = serializer.Deserialize<PassData>(jsonString);
//this serialize in an anonymous object with key value pair
var data2 = serializer.DeserializeObject(textHiddenArguments.Text);
Following is my Json Serialized String
{
"SelectedId":{"0":"ABCD","1":"JKLM"},
"SelectedControlClientId":"YTUTOOO",
"GroupTypeId":3,
"SectionTypeId":"1"
}
quotes escaped string
"{\"SelectedId\":{\"0\":\"ABCD\",\"1\":\"JKLM\"},\"SelectedControlClientId\":\"YTUTOOO\",\"GroupTypeId\":3,\"SectionTypeId\":\"1\"}"
My Problem is Selected Id is array of testWH object. But when I try to desrialize it, the SelectedId property of PassData which is list does not get serialized and count remains zero.
I tried using array instead of List, which gave an exception "no parameter less constructor..."
Could any one explain the what I am doing wrong here ?
The key problem here is that the JSON doesn't match the objects you have constructed. You can see this by writing the data you want and serializing:
var obj = new PassData
{
SelectedId = new List<testWh>
{
new testWh { Id = "ABCD"},
new testWh { Id = "JKLM"}
},
GroupTypeId = "3",
SectionTypeId = "1",
SelectedControlClientId = "YTUTOOO"
};
string jsonString = serializer.Serialize(obj);
which gives JSON like:
{"SelectedId":[{"Id":"ABCD"},{"Id":"JKLM"}],
"SelectedControlClientId":"YTUTOOO","GroupTypeId":"3","SectionTypeId":"1"}
So now you need to decide which you want to change; the JSON or the classes. The following alternative class works fine with your original JSON, for example:
public class PassData
{
public Dictionary<string,string> SelectedId { get; set; }
public string SelectedControlClientId { get; set; }
public string GroupTypeId { get; set; }
public string SectionTypeId { get; set; }
}