I'm using the Newtonsoft Json (http://james.newtonking.com/json) library to deserialize some json into an object but having some trouble with a boolean value. Please see my example below. The example should run in LinqPad as long as you reference the Newtonsoft dll (I'm using the latest at the moment which has a file version of 6.0.3.17227). The issue is deserializing into the UpdateLocationsRequest object.
Any help is appreciated.
void Main()
{
string json1 = "{\"token\":\"5b2a38c8-c211-481e-aa75-7d52fff6eb2f\",\"share\":true}";
string json2 = "{\"token\":\"5b2a38c8-c211-481e-aa75-7d52fff6eb2f\",\"locationList\":[{\"desc\":\"This is a test\",\"name\":\"Andrew 3\",\"deviceLocationId\":\"a8d2bfae-4493-41cd-ae1e-ea0da66da0cf\",\"locType\":1,\"lon\":-80.27543,\"lat\":43.42618,\"share\":true}]}";
TestClass req1 = JsonConvert.DeserializeObject<TestClass>(json1);
UpdateLocationsRequest req2 = JsonConvert.DeserializeObject<UpdateLocationsRequest>(json2);
json1.Dump("json1");
req1.Dump("Boolean ok here");
json2.Dump("json2");
req2.Dump("Boolean not ok here. Why not?");
}
// Define other methods and classes here
public class UpdateLocationsRequest
{
public string token { get; set; }
public List<LocationJson> locationList { get; set; }
}
public class LocationJson
{
public string deviceLocationId { get; set; }
public string name { get; set; }
public string desc { get; set; }
public int locType { get; set; }
public float lat { get; set; }
public float lon { get; set; }
public bool show { get; set; }
}
public class TestClass {
public string token {get; set;}
public bool share {get; set;}
}
Your json bool value is share, but in your class it's show. Adjust one or the other so they match, and you should be good to go
I found your problem. You LocationJson class has a boolean property named show whiles your json2 string has the property share. show is never updated. All other values are updated.
It is always a good thing to add breakpoints and step into your program and see what is going on.
Best of luck.
Related
Hey all I am trying to figure out how to go about saving just one value in my JSON class instead of having to write the whole JSON out again with "New". I am using the Newton JSON.Net.
This is my JSON structure:
public class GV
{
public class Data
{
[JsonProperty("pathForNESPosters")]
public static string PathForNESPosters { get; set; }
[JsonProperty("pathForSNESPosters")]
public static string PathForSNESPosters { get; set; }
[JsonProperty("pathForSEGAPosters")]
public static string PathForSEGAPosters { get; set; }
[JsonProperty("pathToNESContent")]
public static string PathToNESContent { get; set; }
[JsonProperty("pathToSNESContent")]
public static string PathToSNESContent { get; set; }
[JsonProperty("pathToSEGAContent")]
public static string PathToSEGAContent { get; set; }
[JsonProperty("lastSavedVolume")]
public static double LastSavedVolume { get; set; }
}
public class Root
{
public Data data { get; set; }
}
And I have no issues with loading that data from a file into my class:
GV.Root myDeserializedClass = JsonConvert.DeserializeObject<GV.Root>(File.ReadAllText(
currentAssemblyPath + String.Format(#"\Resources\{0}", "dataForLinks.json")
));
But I have yet to find anything searching that will let me do one update to an object in the class without wiping it out doing a New statement.
What I am wanting to do is something like the following:
-Load the json into my class object [Done]
-Save a value thats in my class object [stuck here]
GV.pathToNESContent = "new value here";
-Save class object (with the one new value) back to the file for which it came from preserving the other original values. [not here yet]
When I update just that one class object I am wanting to contain the original values for all the other JSON data I read in from the file.
Anyone have a good example of the above you can share?
update
I'd ditch the inner class structure:
namespace GV
{
public class Data
{
[JsonProperty("pathForNESPosters")]
public string PathForNESPosters { get; set; }
[JsonProperty("pathForSNESPosters")]
public string PathForSNESPosters { get; set; }
[JsonProperty("pathForSEGAPosters")]
public string PathForSEGAPosters { get; set; }
[JsonProperty("pathToNESContent")]
public string PathToNESContent { get; set; }
[JsonProperty("pathToSNESContent")]
public string PathToSNESContent { get; set; }
[JsonProperty("pathToSEGAContent")]
public string PathToSEGAContent { get; set; }
[JsonProperty("lastSavedVolume")]
public double LastSavedVolume { get; set; }
}
public class Root
{
public Data Data { get; set; }
}
Deser (use Path.Combine to build paths, not string concat):
var x = JsonConvert.DeserializeObject<GV.Root>(File.ReadAllText(
Path.Combine(currentAssemblyPath, "Resources", "dataForLinks.json"))
));
Edit:
x.Data.PathToNESContent = "...";
and re-ser
I'm new to this. I'm using Xamarin in VS2017.
I have a JSON file as follows
[ {
"LEDGERID":1,
"LEDGERNAME":"CASH",
"UNDER":"19",
"CREDIT_PERIOD":"0",
"CREDIT_LIMIT":"0",
"LEDGER_TYPE":"DEBIT",
"OPENBAL":120196.00,
"STATUS":"True",
"USER_GEN":false,
"date":null,
"arabic_name":null},
{
"LEDGERID":2,
"LEDGERNAME":"PURCHASE",
"UNDER":"17",
"CREDIT_PERIOD":"0",
"CREDIT_LIMIT":"0",
"LEDGER_TYPE":"DEBIT",
"OPENBAL":0.00,
"STATUS":"True",
"USER_GEN":false,
"date":null,
"arabic_name":null
}
]
This is a lengthier one but i made it short for easy understanding. I need to take it one by one because sometimes I need to give test cases before taking the values to the list. I am using PCL storage in XAMARIN tostore the Json File. I went througn the documents of NewtonSoft Json deserializing. I hope some one can help me thanks in advance
Your json isn't valid, you had the word nul, however i'm sure it was a mistake
Take your json to http://json2csharp.com/ and create a class from it and call it what ever you want
Get your self the Json.net Nuget package
Example class
public class RootObject
{
public int LEDGERID { get; set; }
public string LEDGERNAME { get; set; }
public string UNDER { get; set; }
public string CREDIT_PERIOD { get; set; }
public string CREDIT_LIMIT { get; set; }
public string LEDGER_TYPE { get; set; }
public double OPENBAL { get; set; }
public string STATUS { get; set; }
public bool USER_GEN { get; set; }
public object date { get; set; }
public object arabic_name { get; set; }
}
Usage
var results = JsonConvert.DeserializeObject<List<RootObject>>(json);
passing a Json value like this one(this will be the var jsonValue in code):
"{\"Something\":0,\"Something2\":10,\"Something3\":{\"Something4\":17,\"Something5\":38042,\"Something6\":38043,\"Id\":215},\"Something7\":215,\"SomethingId\":42,\"Something8\":\"AString, Gläser\",\"Something8\":\"44-55-18\",\"Status\":{\"Caption\":\"Fixed\",\"Value\":7},\"Type\":\"Article\",\"Id\":97,\"#Delete\":true,\"Something9\":\"8\"}"
to the following code:
var deserializer = new JsonSerializer();
const string regex = #"/Date\((.*?)\+(.*?)\)/";
var reader = new JsonTextReader(new StringReader(jsonValue));
returnValue = deserializer.Deserialize(reader, type);
type is the typeof https://dotnetfiddle.net/LMPEl0 (thank you Craig) (sorry for the weird names, can't disclose the actual ones...)
The jsonvalue is generated by input in an editable cell of a DataTable and apparently places previously null values in the end of the json string.
I get a null value in the "Something9" property in the returnValue, instead of 8(Something9 was null before and set to 8 through an editable Cell of a DataTable)
Is there some problem with the Json value that I can't see?
Or do I need some setting in the Deserializer?
Thanks
You don't show what your type is so I generated one using http://json2csharp.com.
public class Something3
{
public int Something4 { get; set; }
public int Something5 { get; set; }
public int Something6 { get; set; }
public int Id { get; set; }
}
public class Status
{
public string Caption { get; set; }
public int Value { get; set; }
}
public class RootObject
{
public int Something { get; set; }
public int Something2 { get; set; }
public Something3 Something3 { get; set; }
public int Something7 { get; set; }
public int SomethingId { get; set; }
public string Something8 { get; set; }
public Status Status { get; set; }
public string Type { get; set; }
public int Id { get; set; }
[JsonProperty("#Delete")]
public bool Delete { get; set; }
public string Something9 { get; set; }
}
Because one of your properties has a name that is not valid as a .NET property I added the [JsonProperty] attribute to that one. After that it worked perfectly. Perhaps the problem is with how you declared the #Delete JSON property in your .NET type. Given that Something9 comes after that property it would be my guess that that's part of the problem.
Here's the fiddle.
https://dotnetfiddle.net/McZF9Q
While Craig's answer helped a lot and finally led to a solution the exact answer to the problem was the following:
The Status object is an Enum and was not Deserialized correctly.
Due to that, anything that followed in the Json string was also not deserialized.
Implementing a custom Enum Deserializer was the solution. There are other Questions in stackoverflow that helped with this, particularly this one here:
How can I ignore unknown enum values during json deserialization?
Thank you everyone :)
I want to bind json obect to my properties When I deserialize the json object and bind into the properties ,properties shows null values,please some one help me to resolve this.
this is my code
string s = "{\"response\":{\"status\":\"fail\",\"content\":{\"user_id\":\"56\",\"first\":\"kiran\",\"last\":\"kumar\",\"username\":\"kirankumar\"},\"msg\":\"shggh\"}}";
var jsonObj = JObject.Parse(s);
response myDeserializedObj = (response)Newtonsoft.Json.JsonConvert.DeserializeObject(jsonObj.ToString(), typeof(response));
this is properties
public class response
{
public string status { get; set; }
public content content { get; set; }
}
public class content
{
public string user_id { get; set; }
public string first { get; set; }
public string last { get; set; }
public string username { set; get; }
}
Thanks,
karthik
I copied you code and tested it in my machine and I could solve your problem
here is the solution
add the following class
public class ResponseWrapper
{
public response response { get; set; }
}
replace your code with the following
string s = "{\"response\":{\"status\":\"fail\",\"content\":{\"user_id\":\"56\",\"first\":\"kiran\",\"last\":\"kumar\",\"username\":\"kirankumar\"},\"msg\":\"shggh\"}}";
response my = JsonConvert.DeserializeObject<ResponseWrapper>(s).response;
I am sure this will work.
UPDATE
Another solution (Which is tested also) and better than the first one
because it is more clean, and in this way you have not to create new wrapper class.
the solution is replace your string with the following string.
and all of your previous code will stay the same
here is the correct JSON string
string s = "{\"status\":\"fail\",\"content\":{\"user_id\":\"56\",\"first\":\"kiran\",\"last\":\"kumar\",\"username\":\"kirankumar\"},\"msg\":\"shggh\"}";
UPDATE 2
in the comments below of this answer you asked a completely a new question.
here is your new question (I copied this from your comments)
public class responseWraper
{
public response response { get; set; }
}
public class response
{
public string status { get; set; }
public content content { get; set; }
}
public class content
{
public Employees Employees { get; set; }
}
public class Employees
{
public string Employee_id { get; set; }
public string Employee_name { get; set; }
public string status { get; set; }
}
and here is how you are trying to deserialize this (also this copied from your comments)
string s = "{\"response\":{\"status\":\"success\",\"content\":{\"Employees\":[{\"Employee_id\":\"1\",\"Employee_name\":\"Sravan\",\"status\":\"1\"},}]}}}";
response my = Newtonsoft.Json.JsonConvert.DeserializeObject<responseWraper>(s).response;
ANSWER
your code has two problem
the first is you are using the Employees as array in the JSON string, but the type of the Employees property is not an array
the second problem that the JSON string itself is not valid. it has an errors
there is 4 { character but you have 5 } character inside it.
so you have to fix those two problem as the following
public class content
{
public List<Employees> Employees { get; set; }
}
and the string is
string s = "{\"response\":{\"status\":\"success\",\"content\":{\"Employees\":[{\"Employee_id\":\"1\",\"Employee_name\":\"Sravan\",\"status\":\"1\"},]}}}";
and if you have any other question , I will be happy to help you :)
Try your JSON with http://json2csharp.com/.
Your current code would deserialize the following JSON:
{
"status":"fail",
"content":{
"user_id":"56",
"first":"kiran",
"last":"kumar",
"username":"kirankumar"
},
"msg":"shggh"
}
You are missing a root class with a single Property "response" with the type "Response"
I'm getting a bunch of JSON data back from a 3rd party API like this:
returnValue = data["value"].ToObject<List<T>>();
All but one of the fields are just basic name:value pairs like this:
"Name":"Value"
I map the values I need to a class like this:
public sealed class Project
{
public string Id { get; set; }
public string Title { get; set; }
public string Url { get; set; }
public DateTime ProjectDateLocal { get; set; }
public string ParentFolderName { get; set; }
public string ParentFolderId { get; set; }
//causing trouble
public Int32 ProjectTypeId { get; set; }
public string PlayerUrl
{
get
{
return "http://em.edu.edu/prj/Play/" + this.Id;
}
}
}
However, one name:value pair is complicated like this:
"CustomFieldValues":[
{
"FieldName":"ProjectTypeId","FieldDefinitionId":"37a2ffeb3bd441f6a60158458910a04d40","DataType":"Integer","Value":"100105"
}
]
I only need the FieldName(ProjectTypeId) and Value, is there a way to get just that have the class recognize that and set it in my ProjectTypeId property?
Thanks!
As #viggity stated, you can use Newtonsoft for your problem and the solution provided is good. The only thing you have to do is provide a good string json to the Deserializer.
If you want a simpler solution why don't you use data["value"].ToObject<List<Project>>() ?
Note: Assigning attributes like [JsonProperty("FieldNameFromJson")] is ussefull for mappings.
See this post for more info about how you can do this.
Use Json.net to deserialize JsonConvert.Deserialize<Project>(jsonStringContent)
Json.net will go multi levels, just add a new class and have your Project have that property.
public class CustomFieldValue
{
public string FieldName {get;set;}
public string Value {get; set;}
}
and add a list of them to your Project.
public sealed class Project
{
public string Id { get; set; }
...
public List<CustomFieldValue> CustomFieldValues { get; set; }
}
Json.net won't have any problem with it. If you don't add FieldDefinitionId, etc then Json.net will just ignore it.
http://www.newtonsoft.com/json