I am using GSON on my client to stringy an object:
Gson gson = new Gson();
String data = gson.toJson(deviceInfo);
now I receive this in a header of the http request. I now need to on my server convert it back into the object. I am not parsing it as a param so the modelbinder wont just do it for me. If there is a way to manually use to model binder. then maybe that is an option as well.
How can I do this with json.net ?
basically I want the equivalent of: gson.fromJson(json, classOfT)
The equivalent of gson.fromJson(json, classOfT) in json.net is
JsonConvert.DeserializeObject<T>()
Example:
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
string json = #"{
'Email': 'james#example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account.Email);
Related
I Trying to POST a json data into self hosted WCF service
POST is working good when json string such as
{"data": "testdata"}
same POST is doesn't working and returning 400 (Bad Request) error message when json string as
{data: [{
data1: "testvalue1",
data2: "testvalue2",
data3: "testvalue3",
data4: "testvalue4",
}]
}
And this is my WCF service Code
<OperationContract>
<WebInvoke(Method:="POST", ResponseFormat:=WebMessageFormat.Json, RequestFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.Wrapped)>
Private Function DoWork(ByVal data As string) As system.servicemodel.channels.message
// DO SOMETHING WITH DATA
end function
What is difference between json string and nested json string in my case
And how can i solve my problem
Thanks.
WCF cannot deserialize complex object represented in json into string. In order to make the example work you need to accept a collection of complex objects in operation
//complex object class
[DataContract]
public class DataModel
{
[DataMember(Name = "data1")]
public string Data1 { get; set; }
[DataMember(Name = "data2")]
public string Data2 { get; set; }
[DataMember(Name = "data3")]
public string Data3 { get; set; }
[DataMember(Name = "data4")]
public string Data4 { get; set; }
}
private Message DoWork(List<DataModel> data)
I have the following class...
[JsonObject]
public class Response
{
[JsonProperty]
public RequestStatusCode StatusCode { get; set; }
[JsonProperty]
public String StatusMessage { get; set; }
[JsonProperty]
public Dictionary<String,String> response { get; set; }
[JsonProperty]
public DataSet dataResponse { get; set; }
public Response()
{
StatusMessage = String.Empty;
response = new Dictionary<string, string>();
dataResponse = new DataSet();
}
}
After serialization with JSON.NET using JsonConvert.SerializeObject(myObject) I get the following beautiful JSON string (just an example):
{"StatusCode":0,"StatusMessage":"Succeed.","response":{},"dataResponse":{"Table":[{"LabelID":355,"ProductID":1005,"InternalPN":"111INT","Description":"Produs2","WorkOrderSerialNumber":"0000000005","LabelNumber":1,"BarCode":"P000000000500001","Pallet":true,"LabelStatusID":1,"StatusName":"Printed","UserIDAddStatus":1004,"UserNameAddStatus":"test1","DataAddStatus":"2017-03-15T18:42:27.01","IsValidScan":false}]}}
Well, the problem comes when it's time to recreate the original object using
myObject =JsonConvert.DeserializeObject<Response>(json)
in the DataSet property dataResponse there is no data loaded. All the other properties are ok except this. There is no error, no nothing.
Is there any solution to recreate the original object using JSON.NET?
Thanks a lot!
I have to create a post request in Json in this format.
{
"request": {
"application": "APPLICATION_CODE",
"auth": "API_ACCESS_TOKEN",
"notifications": [{
"send_date": "now", // YYYY-MM-DD HH:mm OR 'now'
"ignore_user_timezone": true, // or false
"content": "Hello world!"
}]
}
}
This is my first time serializing Json String and I have no idea how to do this, I have tried a few different things but could never get the exact format.
Would really appreciate any kind of help.
Thanks!
First, you cannot put comment on a json file, but I guess it was just there for now.
Then you can paste your json in converters like this one http://json2csharp.com/
And you get the following:
public class Notification
{
public string send_date { get; set; }
public bool ignore_user_timezone { get; set; }
public string content { get; set; }
}
public class Request
{
public string application { get; set; }
public string auth { get; set; }
public List<Notification> notifications { get; set; }
}
public class RootObject
{
public Request request { get; set; }
}
Now you need to fix a few issues that are required for JsonUtility:
[Serializable]
public class Notification
{
public string send_date;
public bool ignore_user_timezone;
public string content;
}
[Serializable]
public class Request
{
public string application;
public string auth;
public List<Notification> notifications;
}
[Serializable]
public class RootObject
{
public Request request;
}
Finally:
RootObject root = JsonUtility.FromJson<RootObject>(jsonStringFile);
You can also use SimpleJSON like this ;
string GetRequest () {
JSONNode root = JSONNode.Parse("{}");
JSONNode request = root ["request"].AsObject;
request["application"] = "APPLICATION_CODE";
request["auth"] = "API_ACCESS_TOKEN";
JSONNode notification = request ["notifications"].AsArray;
notification[0]["send_date"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
notification[0]["ignore_user_timezone"] = "true";
notification[0]["content"] = "Hello world!";
return root.ToString ();
}
I have a class as below
public class Person
{
public string Name { get; set; }
[DisplayName ("Please Enter Your Age")]
public int Age { get; set; }
public string Sex { get; set; }
}
I serialized this object to Json using json() of MVC3, but the DisplayName attribute is ignored. I get the json as
"*{"Name":"Person Name","**Age**":28,"Sex":"Male"}*"
Actually i was expecting
"*{"Name":"Person Name","**Please Enter Your Age**":28,"Sex":"Male"}*"
Code converts the object to json
[HttpGet]
public JsonResult JsonTest()
{
Person person = new Person();
person.Age = 28;
person.Name = "Person Name";
person.Sex = "Male";
return (Json(person, JsonRequestBehavior.AllowGet));
}
Any help would be appreciated!!!
You can use the DataContractJsonSerializer to give different names to your properties by using the [DataMember(Name = "myOwnName")] data annotation. Or write your own serializer.
Example can be found here.
Internally the Json method uses the JavaScriptSerializer class to serialize the class into a JSON string. It doesn't allow you to change property names. I guess you will have to roll your own JSON serialization routine. The question is: why do you need that?
I have a class MyItems in my namespace as
[DataContract]
public class MyItems {
[DataMember]
public int LineNum { get; set; }
[DataMember]
public string ItemCode { get; set; }
[DataMember]
public string Priority { get; set; }
[DataMember]
public string Contact { get; set; }
[DataMember]
public string Message { get; set; }
}
and on an XAML I have a button and in its action listener, I am trying to deserialize the JSON string that is coming from a form and trying to update a DataGrid.
In the first step Inside the action listener, I am trying..
List<MyItems> myItems= JSONHelper.DeserializeToMyItems<myItems>(result);
and result (of type string ) has
{"MyItems":[{"LineNum":"1","ItemCode":"A00001","Contact":"5","Priority":"1","Message":"IBM Infoprint 1312"}, {"LineNum":"2","ItemCode":"A00002","Contact":"5","Priority":"1","Message":"IBM Infoprint 1222"}, {"LineNum":"3","ItemCode":"A00003","Contact":"5","Priority":"1","Message":"IBM Infoprint 1226"}, {"LineNum":"4","ItemCode":"A00004","Contact":"5","Priority":"1","Message":"HP Color Laser Jet 5"}, {"LineNum":"5","ItemCode":"A00005","Contact":"5","Priority":"1","Message":"HP Color Laser Jet 4"}]}
The JSONHelper.DeserializeToMyItems code looks like,
public static List<MyItems> DeserializeToMyItems<MyItems>(string jsonString) { MyItems data = Activator.CreateInstance<MyItems>(); using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<MyItems>)); return (List<MyItems>)serializer.ReadObject(ms); } }
While running, I get an exception at the line serializer.ReadObject(ms)
Unable to cast object of type 'System.Object' to type 'System.Collections.Generic.List`1[ServiceTicket.MyItems]'.
I am not sure how to do a type cast for and I am handling a List of type MyItems. Can anyone help me on this please ?. would be highly appreciated as I am new on Silverlight.
thanks
Denny
Try following, it should resolve your problem.
public class JsonHelper
{
public static T Deserialize<T>(string json)
{
using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return (T)serializer.ReadObject(ms);
}
}
}
and use the above method like following:
List<MyItems> myItems = JsonHelper.Deserialize<List<MyItems>>(result);
Hope this helps!