w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
deserialize returns null objects c#
You're trying to deserialize the wrong element - you're trying to deserialize the Access type, whereas your top node is Settings, which is the name applied to the AccessNodes type. Try this instead: AccessNodes settings = SettingsReader<AccessNodes>.Deserialize(...);

Categories : C#

Jackson - Deserialize nested JSON
I see couple of problems in your code. First thing is that you don't have report attribute in your Response class, which is required as per the json structure you have shown. Secondly you need to provide the getters and setters in your bean classes as those will be used by the jackson for marhsalling and unmarshalling of json/object.

Categories : Java

JSON: JsonMappingException while try to deserialize object with null values
If you don't want to serialize null values, you can use the following setting (during serialization): objectMapper.setSerializationInclusion(Include.NON_NULL); Hope this solves your problem. But the NullPointerException you get during deserialization seems suspicious to me (Jackson should ideally be able to handle null values in the serialized output). Could you post the code corresponding to the PersonResponse class?

Categories : Java

JSON Deserialization Despair (unable to deserialize nested types)
I haven't done what you are doing before, but judging by the documentation, I'd assume the following would work: List<Type> types = new List<Type>(); types.Add(typeof(Person)); types.Add(typeof(Language)); types.Add(typeof(Secretary)); DataContractJsonSerializer dc = new DataContractJsonSerializer(typeof(PeopleObject), types); PeopleObject p = (PeopleObject)dc.ReadObject(response); You basically need to tell the Serializer all the types it may encounter while serializing/deserializing your object.

Categories : C#

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type with complex and nested objects
According to your JSON data, the objects that you need to map to have to look like this (unless you have your own JsonDeserializer of course): public class Banner { public string LocationCodeString { get; set; } public int LocationCodeInt { get; set; } public string MediaUrl { get; set; } } public class CampaignWithChosenProposal { public List<Banner> Banners { get; set; } public string Code { get; set; } public string CustomerInstruction { get; set; } public string InfoLink { get; set; } public string LobbySubTitle { get; set; } public string LobbyTitle { get; set; } public string MoreText { get; set; } public int NumOfColumns { get; set; } public int NumOfRows { get; set; } public string OriginString { get; set; } public int

Categories : C#

Serialize deserialize anonymous child JSON properties to model, when some are null
OK this here gave me the solution to the problem How to deserialize object that can be an array or a dictionary with Newtonsoft? public Dictionary<string, string> Location_Options { get { var json = this.LocationsJson.ToString(); if (json == string.Empty | json == "[]") { return new Dictionary<string, string>(); } else { return JsonConvert.DeserializeObject<Dictionary<string, string>>(json); } } } [JsonProperty(PropertyName = "Locations")] public object LocationsJson { get; set; } Many thanks for your help everyone

Categories : C#

Json encode returns null value for some characters
As suggested in this post I add this line: $connectiondb->set_charset('utf8'); the result is the following: {"name":"Mike","surname":"Stern","date":"2013-04-02","session":"1u00b0 session"} This seems a problem cause I want ° and not the relative UTF8 code. But, since the php file is called form ajax I simply setted scriptCharset: "utf-8" and now I can be refer to data.session and obtain "1° session"

Categories : PHP

var_dump of a JSON response returns NULL
Do NOT chain your curl/json calls like that. You're simply assuming we live in a perfect world and nothing could ever fail. That is a very bad decision. Always assume that external resources can and will fail, and check for failure at each stage. Change your code to: $response = curl_exec($ch); if ($result === FALSE) { die("Curl failed with error: " . curl_error($ch)); } $json = json_decode($response, true); if (is_null($json)) { die("Json decoding failed with error: ". json_last_error()); }

Categories : PHP

ASP MVC basic AJAX Json request returns null
An alert will show that, i would suggest using console.log(data) var request = $.ajax({ url: "/Angular/GetQuestion", dataType: "json", type: "post", success: (function (data) { console.log(data); }) }); or as the comments states: var request = $.ajax({ url: "/Angular/GetQuestion", dataType: "json", type: "post", success: (function (data) { alert(JSON.stringify(data)); }) });

Categories : Javascript

json_decode returns NULL for a json data retrieved from an api
Change $sfILE to $sFile $url = 'http://routes.cloudmade.com/81aa79a9504e4430a8a32f491ef96f07/api/0.3/'.$curr_x.','.$curr_y.','.$dest_x.','.$dest_y.'/car.js'; $aContext = array( 'http' => array( 'proxy' => 'tcp://10.3.100.212:8080', 'request_fulluri' => true, 'header' => 'Accept-Charset: UTF-8, *;q=0' ), ); $cxContext = stream_context_create($aContext); $sFile = file_get_contents($url, False, $cxContext); //echo $sFile; $obj = json_decode($sFile); print $obj; print $obj->{'total_time'};

Categories : PHP

JSON jsonObject.optString() returns String "null"
You basically have 2 choices: 1) Send a JSON payload with null values { "street2": "s2", "province": "p1", "street1": null, "postalCode": null, "country": null, "city": null } You will have to check for null values and parse them accordingly: private String optString_1(final JSONObject json, final String key) { return json.isNull(key) ? null : json.optString(key); } 2) Do not send the keys with null values and use optString(key, null) directly (should save you bandwidth). { "street2": "s2", "province": "p1" }

Categories : Java

Nested JSON array returning null In WinRT
I would do it bit differently. First add json.net from NuGet Then add these two classes to your project: public class Course { public int CourseId { get; set; } public string Name { get; set; } } public class Student { public Course Course { get; set; } public int ID { get; set; } public string Name { get; set; } public int Age { get; set; } public string Sex { get; set; } public bool HasScholarship { get; set; } } Now the parsing looks like this HttpClient client = new HttpClient(); HttpResponseMessage response = await client.GetAsync(new Uri("http://localhost:17775/api/Students")); var json = await response.Content.ReadAsStringAsync(); var Students = JsonConvert.DeserializeObject<ObservableCollection<Student>>(json);

Categories : C#

Deserialize multiple JSON arrays into separate C# datasets/datatables using JSON.net (newtonsoft)
This doesn't answer the question exactly because I personally don't see why you would want to deserialize into datasets when the json.NET model is more oriented around deserializing into objects. Here it is; public class TheJson { public string status { get; set; } public client[] clients { get; set; } public dossier[] dossiers { get; set; } } public class client { public string ClientID { get; set; } public string Fullname { get; set; } public bool Inactive { get; set; } } public class dossier { public string CreateDate { get; set; } public string DossierName { get; set; } } With those definitions it's as simple as; TheJson clientsAndDossiers = JsonConvert.DeserializeObject<TheJson>(_jsonresp); Now with regard to your last comment, to ap

Categories : C#

Deserialize JSON Data - Custom Deserialization Using Jackson JSON Parser
UPDATED Among other things, you are mixing up the two aproaches to read a JSON stream: using readTree() to get all your JSON data in a memory tree (like XML's DOM) but also using a JsonParser to read a JSON stream token by token (like XML's JAX). The following is a method that does almost the same using readTree(), which seems to be more appropriate to you as you are reading JSON already loaded in a String: public List<VehicleInformationBean> getAllVehiclesInTree(String response) { List<VehicleInformationBean> vehicleList = new ArrayList<VehicleInformationBean>(); try { PersonInformationBean mPersonInformationBean; DatabaseHelper mDatabaseHelper = DatabaseHelper.getInstance(sContext); ObjectMapper mapper = new ObjectMapper(); O

Categories : Java

JSON.parse returns children objects with null value, children values not being parsed
there are various js libraries predefined for parsing json and to get children values . What i usually do to parse json is use http://developer.yahoo.com/yui/json/ YUI library.

Categories : Javascript

Deserialize the JSON where the values are field names with JSON.NET
You can create a custom JsonConverter which serializes/deserializes Role[]. You can then decorate your Roles property with the JsonConverterAttribute like this: public class User { public string Name { get; set; } [JsonConverter(typeof(RolesConverter))] public Role[] Roles { get; set; } } In your converter class you are able to read an object and return an array instead. Your converter class may look like this: class RolesConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(Role[]); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { // deserialize as object var roles = serializer.Deserialize<JObject>(r

Categories : C#

Very simple attempt to deserialize JSON with JSON.NET does not work
Your JSON has more than one object, and neither are in an array. You either need to remove one of the objects from the JSON or add them to an array and deserialize them properly: string responseBody = @"[ {""HighScoreId"":1,""Name"":""Debra Garcia"",""Score"":2.23}, {""HighScoreId"":2,""Name"":""Thorsten Weinrich"",""Score"":2.65} ]"; var highScores = JsonConvert.DeserializeObject<List<GlobalHighScore>>(responseBody);

Categories : Json

Deserialize deep-nested arrays
It seems there's no built-in way of de-/serializing deep-nested json into anything other than JObject/JArray. So I use strings instead. I suppose one could write a converter to handle everything, however not needed in my case. public class NestedArrayConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value.GetType() == typeof(List<string>)) { var list = (List<string>)value; writer.WriteStartArray(); foreach (var str in list) writer.WriteRawValue(str); writer.WriteEndArray(); } else { writer.WriteValue(value); } } public override object ReadJson(JsonReader reader,

Categories : C#

RestSharp deserialize deeply nested XML document
XML is case-sensitive in the deserialization process. To quickly get around this you can try XML = XML.Replace("COUPON", "Coupon"); etc for each of your element names. If you're going to be processing many different xml files then it will be worth finding something that will do that nicely for you. nb, you could also change the name of your property in Template from Coupon to COUPON

Categories : C#

Get null by deserialize in C# from XML if string between tags
i ran your code on your input and got the output, but the i saw, in the Bits class, that the property entryString has an attribute [XmlElement(ElementName = "Bits")] but in your xml file there is no <Bits> tags around 1st String. so i added them and got: <?xml version="1.0"?> <item name="First Item" size="2"> <Bits value="1"> <Bits>firstOne</Bits> </Bits> <Bits value="2"> <Bits>secOne</Bits> </Bits> </item> and then your code worked so you can change the xml file or get rid of the attribute. your call

Categories : C#

google book api deserialize jsonconvert returning null
You need to convert your json to RootObject and not to VolumeInfo, so this line: var jarray = JsonConvert.DeserializeObject<VolumeInfo>(responseBodyAsText); Becomes this line: var jarray = JsonConvert.DeserializeObject<RootObject>(responseBodyAsText);

Categories : Windows Phone 8

Non-null auto-incrementing column — but 'is null' query returns just-inserted row
Check your "innodb_flush_log_at_trx_commit" system variable and set it to 1 and then try again

Categories : Mysql

deserialize json into .net object using json.net
Sample: var container = JsonConvert.DeserializeObject<ContainerClass>(json); JContainer content = (JContainer)container.ClassContent; switch(container.ClassType) { case "Class1": return container.ToObject(typeof(ClassOne)); .. }

Categories : C#

A better way to deserialize JSON?
How about deserializing the response to an object with all of the properties on each return type and then just checking the values? public class ReturnObject { public YourModel Model {get;set;} public ResultObject ResponseResult {get;set;} public int? MessageType {get;set;} public string Message {get;set;} } string result = eml.PostData("API/Save", dataJSON.ToString()); var returnresult = new JavaScriptSerializer().Deserialize<ReturnObject>(result); { if(returnresult.MessageType.HasValue) { var messageType = returnResult.MessageType.Value; etc etc. } }

Categories : C#

SoapClient Returns "NULL", but __getLastResponse() returns XML
you should give an option parameter as below : <?php // below $option=array('trace',1); // correct one is below $option=array('trace'=>1); $client=new SoapClient('some.wsdl',$option); try{ $client->aMethodAtRemote(); }catch(SoapFault $fault){ // <xmp> tag displays xml output in html echo 'Request : <br/><xmp>', $client->__getLastRequest(), '</xmp><br/><br/> Error Message : <br/>', $fault->getMessage(); } ?> "trace" parameter enables the output of request. Now, you should see the SOAP request. (source: PHP.net

Categories : PHP

How to Deserialize JSON data?
You can deserialize this really easily. The data's structure in C# is just List<string[]> so you could just do; List<string[]> data = JsonConvert.DeserializeObject<List<string[]>>(jsonString); The above code is assuming you're using json.NET. EDIT: Note the json is technically an array of string arrays. I prefer to use List<string[]> for my own declaration because it's imo more intuitive. It won't cause any problems for json.NET, if you want it to be an array of string arrays then you need to change the type to (I think) string[][] but there are some funny little gotcha's with jagged and 2D arrays in C# that I don't really know about so I just don't bother dealing with it here.

Categories : C#

How can I deserialize JSON i Silverlight?
You haven't specified what technologies you use, so I assume that this is a general question about how to parse JSON data in Silverlight. I have written a tutorial in my blog, it is for Windows Phone but will work in Silverlight too. Or you can use the example from MSDN documentation. A general algorithm would be like this: Create model classes with DataContract and DataMember attributes. Use the default serializer class so: new DataContractJsonSerializer(typeof(YourModel)) Parse the stream to your model class (YourModel)dcs.ReadObject(stream) If you have a string instead of a stream, you should convert it to an instance of MemoryStream, it is explained in MSDN documentation. Also you can use other silverlight libraries like JSON.Net for deserializing, but I haven't worked with them

Categories : Json

How to deserialize a JSON array with no name?
Just return an array var locs = Location.DeserializedJson(json); public class Location { public string Precision; public double Latitude; public double Longitude; public string Address; public string City; public string State; public string Zip; public string Country; public static Location[] DeserializedJson(string responseJson) { JavaScriptSerializer jsSerializer = new JavaScriptSerializer(); return jsSerializer.Deserialize<Location[]>(responseJson); } } PS: note that [Serializable]s are unnecessary.

Categories : C#

How to Deserialize JSON string?
The secret is to keep your deserialized JSON in the most general form possible: Dictionary<string, object> theData= new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(jsonString); System.Collections.ArrayList dData= (System.Collections.ArrayList)theData["DData"]; foreach (Dictionary<string, object> data in dData) { string date = (string)data["Date"]; Dictionary<string, object> cZeroNode = (Dictionary<string, object>)data["C0"]; string d = (string)cZeroNode["D"]; string id = (string)cZeroNode["Id"]; } The call to Deserialize() creates a tree of Dictionary<string, object> that you can traverse at will.

Categories : C#

Deserialize JSON to Object
object_hook won't help you, since you have id and name on the different levels in the json string: object_hook, if specified, will be called with the result of every JSON object decoded and its return value will be used in place of the given dict. Let's see why object_hook won't help. If you print objects that are coming to the object_decoder function, you'll see that it is going up from the deep, like this: {u'name': u'bedroom'} {u'name': u'kitchen'} {u'1': None, u'2': None} None This means that you cannot join object_decoder calls in order to produce a Light instance. How about using custom JSONDecoder class instead: import json class Light: def __init__(self, id, name): self.id = id self.name = name response = '{"1": {"name": "bedroom"}, "2": {"na

Categories : Python

Deserialize Json with array
Array of arrays of arrays of arrays of arrays. A pure engineering genius must have designed this data structure. Anyway, here's how to deserialize and access its properties: string json = "[[[[{"string1":"AB","date1":"01/01/1900 8:59:00","date2":"01/01/1900 9:28:00","col":["VO","SC","VD","LF","SR","TT","BN","MM","HH","HH","YY","ZZ"]}],[{"string1":"AB","date1":"01/01/1900 9:02:00","date2":"01/01/1900 9:30:00","col":["VO","SC","VD","LF","LP","VV","FF","MM","HH","HH","YY","ZZ"]}]]]]"; JavaScriptSerializer serializer = new JavaScriptSerializer(); var d = serializer.Deserialize<dynamic>(json); foreach (dynamic item in d[0][0][0]) { Console.WriteLine(item["string1"]); Console.WriteLine(item["date1"]); Console.WriteLine(item["date2"]); ... }

Categories : C#

JSon deserialize DateTime
The javascript Date object is something that is not serializable by .Net, what you do is fix the date before you transfer your object: function fixDate(date) { if (date != undefined && date != null && date.getDate) { var curr_date = date.getDate(); var curr_month = date.getMonth() + 1; //Months are zero based var curr_year = date.getFullYear(); date = curr_date + "/" + curr_month + "/" + curr_year; date = date.replace(/d/g, '0$&'); } return date; } this code is for the "dd/MM/yyyy" format , but you can format it how ever you like. remember to choose the specific format in your server as well

Categories : C#

Deserialize JSON to subclasses
Here is converter for your person class. It gets IsFemale field value, and based on it creates Female or Male person, which is populated by serializer: public class PersonConverter : JsonConverter { public override bool CanConvert(Type objectType) { return typeof(Person).IsAssignableFrom(objectType); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JObject jObject = JObject.Load(reader); var isFemale = (bool)jObject["IsFemale"]; Person target = isFemale ? (Person)new Female() : new Male(); serializer.Populate(jObject.CreateReader(), target); return target; } public override void WriteJson(JsonWriter writer, object value, Jso

Categories : C#

Newtonsoft JSON Deserialize
You can implement a class that holds the fields you have in your JSON class MyData { public string t; public bool a; public object[] data; public string[][] type; } and then use the generic version of DeserializeObject: MyData tmp = JsonConvert.DeserializeObject<MyData>(json); foreach (string typeStr in tmp.type[0]) { // Do something with typeStr } Documentation: Serializing and Deserializing JSON

Categories : C#

JSON.Net Deserialize MailAddress
I think the problem is that your ReadJson method leaves the reader incorrectly positioned when it is finished, thus messing up the rest of the deserialization process. Think of the reader like a forward-only cursor for the JSON data. When ReadJson gets called, it is positioned such that it is just about to read the next item that the converter said it can handle. In the case of your EmailConverter, it would be positioned just about to read this portion of the JSON: { "DisplayName": "", "User": "jamesdean890", "Host": "fake.com.au", "Address": "jamesdean890@fake.com.au" } Since the converter is supposed to handle the entire Email object, it needs to consume all the JSON for that object. I think what is happening is the reader is not getting advanced to the closing brace. You

Categories : Vb.Net

Deserialize json with converter
Given the object you want to convert, you can use the ToObject<T>() to get the converted object. In your case, you want to convert the second item in the array to a MetaData object. public class DeltaEntryConverter : JsonConverter { public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var arr = (JArray)serializer.Deserialize(reader); return new DeltaEntry { Path = (string)arr[0], MetaData = arr[1].ToObject<MetaData>(), }; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } public override bool CanConvert(Type objectType) { thr

Categories : Dotnet

Can't deserialize JSON string in .NET
Add an empty Namespace to the DataContract attribute used to decorate your Identifier class: [DataContract(Namespace = "")] public class Identifier { [DataMember] public string Version { get; set; } [DataMember] public string Value { get; set; } [DataMember] public int IdentifierType { get; set; } } The reason you need this is because of the __type attribute that is used in your JSON and which has a special meaning for the serializer.

Categories : C#

python json.loads / json.load truncates nested json objects?
JSON doesn't care about the keys for objects, but the json.load and json.loads convert to a Python object using this conversion table. JSON objects are turned into python dict's, which means you can't have repeated keys.

Categories : Python

Deserialize JSON property name with @ sign
Just tried your code and i get the desired result. Version of Json.Net was 4.5.10.15407. string jsonString = @"{ ""@start"":""0"", ""@totalRecords"":""1"", ""@queryTime"":""0"" }"; SearchResult result = JsonConvert.DeserializeObject<SearchResult>(jsonString); Check if theres a problem in the input json string (quoting, encoding or whatsoever) or if maybe its a bug in the version of Json.Net you use.

Categories : C#

Deserialize json character as enumeration
This code works perfectly: CardType[] array = { CardType.Artist, CardType.Contemporary }; string s = JsonConvert.SerializeObject(array); var array2 = JsonConvert.DeserializeObject<CardType[]>(s); Update: What about out-of-box StringEnumConverter: [JsonConverter(typeof(StringEnumConverter))] public CardType Type { get; set; }

Categories : C#



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.