w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
JSON serializer with nested object lists
Turns out you don't need to use a serializer at all. You just return type object. public object NavigationItems() { using (TTConnection connection = new TTConnection("ClientDb")) { if (MySession.Current.MyClub == null) return USER_ERROR; MiddleTier.WebNavigation.WebNavigationGenerator gen = MySession.Current.NavGenerator; List<NavigationElement> list = gen.GetNavigation(); return list; } }

Categories : C#

Why is no constructor needed of the object, deserialized from a json string, using ServiceStack Json Serializer
Default (no parameters) constructor is created by the compiler if no constructors are specified. The compiler does that when and only when NO constructors exist. If you create ANY constructor in your class this compiler behaviour will no longer apply. (Try creating a constructor with at least one parameter to see what will happen) Deserialization will involve two steps - create empty object using default (no parameters) constructor and than set all values. If you class does NOT have default (no parameters) constructor - either created by yourself explicitly or by the compiler - deserialization will fail. Deserialization never uses parametrised constructors as it is impossible for it to guess the correct constructor to use. Example: deserialization can not distinguish between Constructor

Categories : C#

when we serialize serializable object using JSON.Net, JSON string is different from DatacontractJSON serializer
Unless you are always communicating from WCF to WCF, your best bet is probably going to be to use the Newtonsoft serializer. Unfortunately, the MS serializer seems to follow some Microsoft-specific standards that do not match the standards that many web apps expect. Newtonsoft's serializer seems to be more standard, and even MS uses it for WebAPI, and in the Web API http client (nuget will pull it down for you). Here's another difference that you will find -- try serializing a DateTime type. You will find that the DataContract serialzer serializes the value in a different format that is not compatible with other JSON (you will notice some slashes in it). My understanding is that that alternate format was used by some of the AJAX WebForm controls, but it's specific to Microsoft Webforms

Categories : C#

What is the difference between JSON.NET DataContractJsonSerializer and the Newtonsoft JSON serializer
You can find the comparison of the performance here Here is the feature comparison, http://james.newtonking.com/projects/json/help/index.html?topic=html/JsonNetVsDotNetSerializers.htm

Categories : C#

Jackson JSON help (Serializer)
You can achieve your goals using two ways: simple and complex. Simple: You can create new POJO classes with fields which you need. After that, you have to convert your library objects into new into new POJO objects and, finally, serialize it using Jackson or Gson library. Complex: You can write new serializer/deserializer for your library classes, but this solution is much complicated. Helpful links: How do I use a custom Serializer with Jackson? Using Custom Serializers with Jackson Jackson How-To: Custom Serializers

Categories : Json

RSpec Rails Serializer JSON
We've gone and basically rolled our own matchers because the JSON serializers weren't working for us either. They're a bit involved, so I've added them to a gist: https://gist.github.com/gavingmiller/e03ff13edfeef8d5c08d The example tests end up looking like this: require 'spec_helper' describe FeedSerializer, type: :serializer do it { should have_attribute(:id) } it { should have_attribute(:name) } it { should have_many_relation(:feed_filters) } end When we make modifications to the serializers (ie: different output than just straight attributes) our tests look like this: it "successfully parses JSON as an additional field" do @data = '{ "key": "value" }' json = FooBarSerializer.new(data).as_json json[:foo][:bar]['key'].should == 'value' end

Categories : Ruby On Rails

JSON use child object in serializer
The simpliest way to generate JSON String is to use method .writeObject(objName), which autogenerate fields and their values. If you need other name of values or exclude values from generation or format string, than you can use standart declaration.

Categories : Java

DataContract Name Attribute not Working with Json Serializer
Arrays don't have names by themselves in JSON. If you want a name on the list, you need an outer object that has a named property to hold the list. Something like this: public class Response { [DataMember(Name = "Files")] List<FileDesc> FileList { get; set; } } The JSON would then look like this: { "Files": [ { "myFileName": ""ArduinoUNO.png"", "myFilePath": "c:\images\ArduinoUNO.png", "myFileSize": null } ] }

Categories : Asp Net

Custom Json.NET serializer settings per type
Based on your comment above, following is an example of per-controller configuration: [MyControllerConfig] public class ValuesController : ApiController [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public class MyControllerConfigAttribute : Attribute, IControllerConfiguration { public void Initialize(HttpControllerSettings controllerSettings, HttpControllerDescriptor controllerDescriptor) { //remove the existing Json formatter as this is the global formatter and changing any setting on it //would effect other controllers too. controllerSettings.Formatters.Remove(controllerSettings.Formatters.JsonFormatter); JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter(); formatter.SerializerSettings.

Categories : C#

ASP.NET json serializer only includes __type for top level class
I encountered a similar situation with another JSON serializer, the one from ServiceStack.Text. They will put in the __type property if an object is declared as an interface or an abstract class, perhaps the vanilla .NET serializer will do so as well? If that's the case, is there any way for you to declare your object[] array as an array of interfaces? Even something as trivial as cerating an IEmpty with no methods will do the trick.

Categories : Asp Net

Custom JodaTime serializer using Play Framework's JSON library?
There is a default DateTime serializer, but it uses dt.getMillis instead of .toString which would return an ISO compliant String. If you look at the source, Reads.jodaDateReads already handles both numbers and strings using DateTimeFormatter.forPattern. If you want to handle ISO8601 string, just replace it with ISODateTimeFormat: implicit val jodaISODateReads: Reads[org.joda.time.DateTime] = new Reads[org.joda.time.DateTime] { import org.joda.time.DateTime val df = org.joda.time.format.ISODateTimeFormat.dateTime() def reads(json: JsValue): JsResult[DateTime] = json match { case JsNumber(d) => JsSuccess(new DateTime(d.toLong)) case JsString(s) => parseDate(s) match { case Some(d) => JsSuccess(d) case None => JsError(Seq(JsPath()

Categories : Json

Spring MVC: Applying different JSON serializer for different annotated controller method
want the JSON representation of the {{Foo}} to be different for those methods Well you'll definitely need different serializers and foos. There is no getting away from the fact. And its preferable imho.

Categories : Spring

Rails Active Model Serializer — need to manipulate rendered json prior to send
The issue here is that your "sessions" variable refers to an array and not a session object. What you are doing would have worked perfectly for a single session (of class SessionResume) but for an array you need to do something like the following: sessions = ended_sessions.where("current_date <= (created_at + interval '12 hours')") json = JSON.parse(ActiveModel::ArraySerializer.new(sessions).as_json) json.each do |session| # additional processing end Note that you need to use ActiveModel::ArraySerializer rather than the class specific, single-object serializer.

Categories : Ruby On Rails

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

nested json with jQuery: create List of nested item
Your problem is that institut is an array containing a single object, so you can reference that single object using institut[0]. This will work: $.each(data.fakultaeten, function (key, value) { var mother = "<li id='first'>" + value.name + "<ul>"; $.each(value.institut[0], function (key1, value1) { alert(key1); }); }); Here is a working example

Categories : Jquery

Avoiding nested each loops when handling nested JSON data
JSON is "just" javascript object literals. You can skip the jQuery call, and just reference the objects and arrays directly after you parse it. obj.custom_sql_rule[0].something_else[0]; of course, your JSON is a bit oddly-formed. If at all possible, don't arbitrarily mix objects {} and arrays [] . Use the latter when you have lists of identical objects or primitive data, and the former when you have named properties. And once you have a valid javascript object, you can just iterate through its properties. for(var sqlProp in jsonObj) { if(jsonObj[sqlProp].error) { errorsContainer.append("<div>" + jsonObj[sqlProp].error + "</div>"); } }

Categories : Javascript

Cannot see the Restangular response data set in my chrome developer tools... is it bc my JSON contains nested JSON?
I'm the creator of Restangular. So, when you're doing a getList, Restangular expects to get an Array as the response. In your case, when you're getting a list and the path is availableCourses, you're returning a string (the title) which has properties. So you're creating a "special" string with properties, it's not really common, nor compatible with Restangular. If you want to get the list of all available courses, you need to return an array as the new response. So, what's the exact response from the server when you do the getList? If you giv eme that, I'll be able to help you easier on how to create this response extarctor. Also take a look to this MongoLab example :), maybe It'll help you. http://plnkr.co/edit/d6yDka?p=preview Bests!

Categories : Angularjs

Is it possible to create nested JSON objects in haskell using Text.JSON?
Text.JSON allows you to nest objects, as you can see by the type definition: data JSValue = JSNull | JSBool !Bool | JSRational !Rational | JSString JSString | JSArray [JSValue] | JSObject (JSObject JSValue) newtype JSObject e = JSONObject { fromJSObject :: [(String, e)] } The type is recursive - JSValues may be JSObjects which in turn may be dictionaries of JSValues.

Categories : Json

Nested arrays in JSON
I'm not sure what is the question, but an object like that would be this: { X : [ { id: "1", name: "Student z", }, { id: "2", name: "Student b", } ], N : [ { id: "3", name: "Student c", }, { id: "4", name: "Student a", } ] } Is that what you wanted?

Categories : PHP

Json nested parameters
Try this. var actionLinks = new List<string>(); var actions = post["actions"] as JArray; // if this works then all is well foreach(var item in actions) { actionLinks.Add((string)item["link"]); } I think you can also use some fancy Linq with this like var actionLinks = ((JArray)post["actions"]) .Children<JObject>() .Select(a => (string)a["link"]) .ToList(); Very un-tested. Just let me know.

Categories : C#

Nested JSON From PHP Array
Call array_values on your array: $data = json_encode(array_values($info)); This removes your named indexes and converts them to numerical ones instead, so json_encode should treat your array as an indexed (and not an associative) array.

Categories : PHP

deserialise nested xml via json.net
When you use JsonConvert.SerializeXmlNode(doc) to transform your XML document to a JSON string, the JSON that is generated looks like this: { "?xml": { "@version":"1.0" }, "Parameters": { "AParameters": { ... }, "BParameters": { ... } } } Note that the Parameters data is not at the root, but is inside an outer object. So when you try to deserialize the JSON directly into a Parameters class, none of the properties line up because they are all one level further down. Since JSON.Net is unable to match up the field names in the class to the JSON data, it simply uses default values. To fix this you can do one of two things. 1) Fix your XML to JSON transformation so that the Parameter

Categories : C#

Create nested JSON from CSV
The csv module will handle the CSV reading nicely - including handling line breaks that are within quotes. import csv with open('my_csv.csv') as csv_file: for row in csv.reader(csv_file): # do work The csv.reader object is an iterator - you can iterate through the rows in the CSV by using a for loop. Each row is a list, so you can get each field as row[0], row[1], etc. Be aware that this will load the first row (which just contains field names in your case). As we have field names given to us in the first row, we can use csv.DictReader so that fields in each row can be accessed as row['id'], row['name'], etc. This will also skip the first row for us: import csv with open('my_csv.csv') as csv_file: for row in csv.DictReader(csv_file): # do work For the JSON export

Categories : Python

Nested JSON parse with facebook sdk
Im not sure if this is exaclty correct as i cant test it right now, but it should work in this way. dont forget to check if there is a property called "likes" and if there is an array called "data" in the json representation before using it to prevent NullPointers though. List<String> likes = new ArrayList<String>(); JSONObject jsonLikes = (JSONObject) user.getProperty("likes"); JSONArray jsonData = (JSONArray) likes.getProperty("data"); for(int i = 0; i < data.length(); i++) { likes.add(jsonData.optString("name"); } the list likes then contains all "name" attributes of the likes.

Categories : Java

JSON (de)serializing for nested classes
class YEncoder(json.JSONEncoder): def encode(self, obj): return json.dumps({ 'm': json.dumps({ k: json.dumps(v, cls=XEncoder) for k, v in obj.m.items()})}) class YDecoder(json.JSONDecoder): def decode(self, json_string): y.m = {k: json.loads(v, cls=XDecoder) for k, v in json.loads(json.loads(json_string)['m']).items()} return y

Categories : Python

JSON PHP cant navigate through nested arrays
The false is being treated as a boolean and not a string when you read in the value. PHP shows nothing when you try to echo out a boolean false (e.g. try a print false;). You could also verify this further by comparing the print_r output to var_dump output, e.g.: Interactive shell php > var_dump(false); bool(false) php > print_r(false); php > See this question for a possible solution: How to Convert Boolean to String The basic overview is that you need to test the value, then output a string.

Categories : PHP

Nested JSON data from MySQL
json_encode is obviously the better way than your previous solution. An example would be like this, perhaps $mainarray = array(); foreach($items as $k => $v) { array_push($v,$mainarray); } echo json_encode($mainarray);

Categories : PHP

Getting values from nested JSON document
In your function you need to assign the value returned by get_value: get_value(dataObject[i], keyName); Should be: value = get_value(dataObject[i], keyName); Alternatively, just return the value: return get_value(dataObject[i], keyName);

Categories : Javascript

backbone parse nested json
First of all, that JSON structure is really, truly bizarre. Fix your server or ask your server team to seek therapy. But assuming you can't un-ridiculousify the server's JSON, here's how to make it into a backbone-compatible array: var HotelsCollection = Backbone.Collection.extend({ model: Hotel, url: "includes/test-data.json", parse: function(response){ //remove prefix/wrapper object and collect "hotel" 1-element arrays var sillyArrays = _.pluck(response.hotels, 'hotel'); //Extract the hotel objects from their silly 1-element arrays //Synthesize a fake id attribute since backbone expects that var hotels = _.map(sillyArrays, function (hotelArray, index) { return {name: hotelArray[0].name, id: index + 1}; }); return hotels; } }); That parse fu

Categories : Jquery

Knockout map nested JSON array
You can map your object from the root of the array and process each item and separated objects. You can even have another mapper inside your object and continue processing data with nested mappers //mapper method mapCollection = { '': { create: function (options) { return new objectWithAnotherMapper(options.data); } } },

Categories : Jquery

json object with nested objects
Just create an array. And push the object into an array. var obj = {}; obj["0"] = "1"; obj["2"] = "3"; var wObj = {}; wObj["0"] = obj; console.log(wObj); This is nested object example. Check Fiddle 2nd Example object inside an array var obj = {}; obj["0"] = "1"; obj["2"] = "3"; var wObj = []; wObj.push(obj); console.log(wObj); Array Fiddle

Categories : Jquery

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

nested json in backboneJS view
Since the drilldown is directly set as a model attribute, you would first use model.get('drilldown'). Then we get to data as a property with model.get('drilldown').data and then iterate over the data property which is an array: for (var i = 0, data = model.get('drilldown').data; i < data.length; i++) { // Each array element data[i] has a x and y property console.log(data[i].x, data[i].y); // Logs 1.3722057e+12, 67.84 }

Categories : Json

Getting json data from a nested array
So close! translated.data.translations[0].translatedText; translations is an array of objects, and you want the translatedText property of the first element in the array. UPDATE: Just to confirm the output of to_Translate.responseText is a string containing: { "data": { "translations": [ { "translatedText": "some stuff that's been translated" } ] } } So you should be able to do: var translated = to_Translate.responseText, parsed = JSON.parse(translated), text = parsed.data.translations[0].translatedText; console.log(text);

Categories : Javascript

Getting particular nested items from JSON (objective-c)
OK, first thing to do is drop any third party frameworks for JSON. There is now a native JSON class... NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding: NSUTF8StringEncoding] options:0 error:nil]; NSArray *users = dictionary[@"users"]; Once you've done this you can iterate the users array like you would any other array. Each object in the users array is an NSDictionary with keys @[@"id", @"name"] e.g. for (NSDictionary *userDict in users) { NSLog(@"User name = %@", userDict[@"name"]); }

Categories : Objective C

Rails JSON Nested Attributes
Looks like the JSON has the string 'identifier' as a key whereas you are trying to access it with a symbol :identifier, which returns nil. So [] is not defined on nil. You should probably do parameters["identifier"]["name"].

Categories : Ruby On Rails

JSON Loop through nested array
This is pretty basic stuff var personsMarkup = ""; for (var i in persons){ if (persons.hasOwnProperty(i)){ console.log(i); // the key console.log(persons[i]); // the value // cancat this all together personsMarkup =+ "<li><p>"+i+"</p><p>"+persons[i]+"</p></li>"; } } and then: $('#reports').append( /* ... */ '<ul class="report-moreinfo">' + personsMarkup + '</ul>'; /* ... */ );

Categories : Javascript

Parsing nested JSON entries
You are close. You need: NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData: jsonResponse options: NSJSONReadingMutableContainers error: &e]; NSArray * responseArr = jsonArray[@"SongDeviceID"]; for (NSDictionary *dict in responseArr) { // dict has two keys - SID and SDID }

Categories : IOS

Knockout mapping for nested json
The code is absolutely not clean, but it seems to work: http://jsfiddle.net/ezg5U/ Basically, I track the path within the json data and dynamically set KO bindings like data-bind="'text: values()[0]._values()[1].key'" Also the textarea elements have the "value: " binding, thus storing the updated data in the view model. The DIV below the table is updated automatically and shows the value of the nested key: vm.values()[0]._values()[0].key() - so you can see that the model is actually updated when a user changes the value.

Categories : Javascript

Check value of nested json response
One way you could do this would be to leverage NSPredicate and Key-Value Coding: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"close.day = %@", dayOfWeek]; NSArray *output = [periods filteredArrayUsingPredicate:predicate]; NSNumber *closingTime = [output.lastObject valueForKeyPath:@"close.time"];

Categories : IOS



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