Search Results

Search found 5856 results on 235 pages for 'json encode'.

Page 28/235 | < Previous Page | 24 25 26 27 28 29 30 31 32 33 34 35  | Next Page >

  • Jackson object mapping - map incoming JSON field to protected property in base class

    - by Pete
    We use Jersey/Jackson for our REST application. Incoming JSON strings get mapped to the @Entity objects in the backend by Jackson to be persisted. The problem arises from the base class that we use for all entities. It has a protected id property, which we want to exchange via REST as well so that when we send an object that has dependencies, hibernate will automatically fetch these dependencies by their ids. Howevery, Jackson does not access the setter, even if we override it in the subclass to be public. We also tried using @JsonSetter but to no avail. Probably Jackson just looks at the base class and sees ID is not accessible so it skips setting it... @MappedSuperclass public abstract class AbstractPersistable<PK extends Serializable> implements Persistable<PK> { @Id @GeneratedValue(strategy = GenerationType.AUTO) private PK id; public PK getId() { return id; } protected void setId(final PK id) { this.id = id; } Subclasses: public class A extends AbstractPersistable<Long> { private String name; } public class B extends AbstractPersistable<Long> { private A a; private int value; // getter, setter // make base class setter accessible @Override @JsonSetter("id") public void setId(Long id) { super.setId(id); } } Now if there are some As in our database and we want to create a new B via the REST resource: @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Transactional public Response create(B b) { if (b.getA().getId() == null) cry(); } with a JSON String like this {"a":{"id":"1","name":"foo"},"value":"123"}. The incoming B will have the A reference but without an ID. Is there any way to tell Jackson to either ignore the base class setter or tell it to use the subclass setter instead? I've just found out about @JsonTypeInfo but I'm not sure this is what I need or how to use it. Thanks for any help!

    Read the article

  • highcharts correct json input

    - by Linus
    i am trying to do a basic column chart. i have looked the examples but not sure why i do not see any graph (lines). I can see the title and subtitle appear an no javascript errors in firebug. any help please $(function () { var chart; $(document).ready(function() { chart = new Highcharts.Chart({ chart: { renderTo: 'container', type: 'column', events: { load: requestData } }, title: { text: 'Some title' }, subtitle: { text: 'subtitle' }, xAxis: { categories: [], title: { text: null } }, yAxis: { min: 0, title: { text: 'y-Axis', align: 'high' } }, tooltip: { formatter: function() { return ''+ this.series.name +': '+ this.y +' '; } }, plotOptions: { bar: { dataLabels: { enabled: true } } }, legend: { layout: 'vertical', align: 'right', verticalAlign: 'top', x: -100, y: 100, floating: true, borderWidth: 1, backgroundColor: '#FFFFFF', shadow: true }, credits: { enabled: false }, series:[] }); }); function requestData() { $.ajax({ url: 'test.json', success: function(data) { options.series[0].push(data); chart.redraw(); }, cache: false }); } }); my json input file is below [ { name: 'name1', y: [32.6,16.6,1.5] }, { name: 'name2', y: [6.7,0.2,0.6] }, { name: 'name3', y: [1,3.7,0.7] }, { name: 'name4', y: [20.3,8.8,9.5] },{ name: 'name5', y: [21.5,10,7.2] }, { name: 'name6', y: [1.4,1.8,3.7] }, { name: 'name7', y: [8.1,0,0] }, { name: 'name8', y: [28.9,8.9,6.6] } ]

    Read the article

  • deserialize Json using JavaScriptSerializer Custom Types

    - by Dave
    I have a RESTFUL WCF service returning a .NET custom type as json string. I am using .NET 3.5 framework and I am using JavaScriptSerializer for deserializing it in to my custom type. Serialization to json is handled by WCF. using (WebResponse resp = req.GetResponse()) { using (System.IO.StreamReader sreader = new System.IO.StreamReader(resp.GetResponseStream())) { string jsonString = sreader.ReadToEnd(); CustomType myType = new CustomType(); System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); myType = serializer.Deserialize<CustomType>(jsonString); return myType; } } The problem is that, I have a property (or element) of the CustomType which is generic list of another custom type ChildObject. They are in different namespaces. When I deserialize using the code above, I get all the properties of the CustomType myType including a list of ChildObject. But all the properties of the ChildObject is null. The string returned from the stream reader has all the values for the ChildObject. the values are lost when deserializing. Can anyone help me with this please?

    Read the article

  • Problem with XStream Marshalling to return xml and json

    - by MiKu
    When i use new XStream().toXml(someObject); it returns following xml... <response> <status>SUCCESS</status> <isOwnershipVerified class="boolean">false</isOwnershipVerified> </response> and, when i use new XStream(new JsonHierarchicalStreamDriver()).toXml(someObject); it returns following json... {"response": { "status": "SUCCESS", "isOwnershipVerified": { "@class": "boolean""false"} }} Now, since i want to get rid of class attribute altogether (read it not to alias it with anything else, but to remove it) i use following code. XStream xStream = new XStream(); StringWriter writer = new StringWriter(); xStream.marshal(this, new PrettyPrintWriter(writer) { @Override public void addAttribute(final String key, final String value) { if (!key.equals("class")) { super.addAttribute(key, value); } } }); return writer.toString(); which gives follwing xml... <response> <status>SUCCESS</status> <isOwnershipVerified>false</isOwnershipVerified> </response> but, when i pass new JsonHierarchicalStreamDriver() while xStream object creation above, it does NOT return json. it returns the same xml shown above. What is wrong going on here? Thanks in advance...

    Read the article

  • Newtonsoft JSON Interface Serialization error

    - by Ben
    I am using C# .NET 4.0, Newtonsoft JSON 4.5.0. public class Recipe { [JsonProperty(TypeNameHandling = TypeNameHandling.All)] public List<IFood> Foods{ get; set; } ... } I want to serialize and deserialize this Recipe object. If I serialize and deserialize the object during application lifetime this succeeds, but if I serialize the object, exit application and then deserialize it then it throws an exception, that it cannot instantiate IFood (since it is an interface). The problem is that it does not serialize the implementation of interface. "$type": "System.Collections.Generic.List`1[[NSM.Shared.Models.IFood, NSMShared]], mscorlib" I tried using TypeNameHandling.Object and Array and Auto, but it didn't help. Is there any way to serialize it properly? Or at least to define the class mapping before deserializing? EDIT: I am using JSON coupled with Hammock ( http://code.google.com/p/relax-net/ ), C# driver for CouchDB, which internally serializes and deserializes objects. As mentioned the problem is that it does not serialize the interface implementation.

    Read the article

  • Web Workers - Transferable Objects for JSON

    - by kclem06
    HTML 5 Web workers are very slow when using worker.postMessage on a large JSON object. I'm trying to figure out how to transfer a JSON Object to a web worker - using the 'Transferable Objects' types in Chrome, in order to increase the speed of this. Here is what I'm referring to and appears it should speed this up quite a bit: http://updates.html5rocks.com/2011/12/Transferable-Objects-Lightning-Fast I'm having trouble finding a good example of this (and I don't believe I want to use an ArrayBuffer). Any help would be appreciated. I'm imagining something like this: worker = new Worker('workers.js'); var large_json = {}; for(var i = 0; i < 20000; ++i){ large_json[i] = i; large_json["test" + i] = "string"; }; //How to make this call to use Transfer Objects? Takes approx 2 seconds to serialize this for me currently. worker.webkitPostMessage(large_json);

    Read the article

  • Using a Javascript Variable & Sending to JSON

    - by D Franks
    Hello all! I'm trying to take a URL's hash value, send it through a function, turn that value into an object, but ultimately send the value to JSON. I have the following setup: function content(cur){ var mycur = $H(cur); var pars = "p="+mycur.toJSON(); new Ajax.Updater('my_box', 'test.php', { parameters: pars }); } function update(){ if(window.location.hash.length > 0){ content(window.location.hash.substr(1)); // Everything after the '#' } } var curHashVal = window.location.hash; window.onload = function(){ setInterval(function(){ if(curHashVal != window.location.hash){ update(); curHashVal = window.location.hash; } },1); } But for some reason, I can't seem to get the right JSON output. It will either return as a very large object (1:"{",2:"k") or not return at all. I doubt that it is impossible to accomplish, but I've exhausted most of the ways I can think of. Other ways I've tried were "{" + cur + "}" as well as cur.toObject(), however, none seemed to get the job done. Thanks for the help!

    Read the article

  • jqGrid Sort or Search does not work with columns having json dot notation

    - by rsmoorthy
    I have this jqGrid: $("#report").jqGrid( { url: '/py/db?coll=report', datatype: 'json', height: 250, colNames: ['ACN', 'Status', 'Amount'], colModel: [ {name:'acn', sortable:true}, {name:'meta.status', sortable:true}, {name:amount} ], caption: 'Show Report', rownumbers: true, gridview: true, rowNum: 10, rowList: [10,20,30], pager: '#report_pager', viewrecords: true, sortname: 'acn', sortorder: "desc", altRows: true, loadonce: true, mtype: "GET", rowTotal: 1000, jsonReader: { root: "rows", page: "page", total: "total", records: "records", repeatitems: false, id: "acn" } }); Notice that the column 'meta.status' is in JSON dot notation and accordingly the data sent from the server is like this: {"page": "1", "total": "1", "records": "5", "rows": [ {"acn":1,"meta": {"status":"Confirmed"}, "amount": 50}, {"acn":2,"meta": {"status":"Started"}, "amount": 51}, {"acn":3,"meta": {"status":"Stopped"}, "amount": 52}, {"acn":4,"meta": {"status":"Working"}, "amount": 53}, {"acn":5,"meta": {"status":"Started"}, "amount": 54} ] } The problems are of two fold: Sorting does not work on columns with dot notation, here "meta.status". It does not even show the sortable icons on the column header, and nothing happens even if the header is clicked. Sorting does not work, whether loadonce is true or false. If I try Searching (after setting loadonce to true) for the column meta.status (other columns without dot notation is okay), then it throws up a javascript error like this. Any help? Thanks Moorthy

    Read the article

  • Turning a JSON list into a POJO

    - by Josh L
    I'm having trouble getting this bit of JSON into a POJO. I'm using Jackson configured like this: protected ThreadLocal<ObjectMapper> jparser = new ThreadLocal<ObjectMapper>(); public void receive(Object object) { try { if (object instanceof String && ((String)object).length() != 0) { ObjectDefinition t = null ; if (parserChoice==0) { if (jparser.get()==null) { jparser.set(new ObjectMapper()); } t = jparser.get().readValue((String)object, ObjectDefinition.class); } Object key = t.getKey(); if (key == null) return; transaction.put(key,t); } } catch (Exception e) { e.printStackTrace(); } } Here's the JSON that needs to be turned into a POJO: { "id":"exampleID1", "entities":{ "tags":[ { "text":"textexample1", "indices":[ 2, 14 ] }, { "text":"textexample2", "indices":[ 31, 36 ] }, { "text":"textexample3", "indices":[ 37, 43 ] } ] } And lastly, here's what I currently have for the java class: protected Entities entities; @JsonIgnoreProperties(ignoreUnknown = true) protected class Entities { public Entities() {} protected Tags tags; @JsonIgnoreProperties(ignoreUnknown = true) protected class Tags { public Tags() {} protected String text; public String getText() { return text; } public void setText(String text) { this.text = text; } }; public Tags getTags() { return tags; } public void setTags(Tags tags) { this.tags = tags; } }; //Getters & Setters ... I've been able to translate the more simple objects into a POJO, but the list has me stumped. Any help is appreciated. Thanks!

    Read the article

  • How do I use HttpWebRequest GET method w/ ContentType="application/json"

    - by Stephen Patten
    Hello, This one is real simple, run this Silverlight4 example with the ContentType property commented out and you'll get back a response from from my service in xml. Now uncomment the property and run it and you'll get an ProtocolViolationException, what should happen is the service returns JSON formatted data. HttpWebRequest wreq = (HttpWebRequest)WebRequestCreator.ClientHttp.Create(new Uri("http://stephenpattenconsulting.com/Services/GetFoodDescriptionsLookup(2100)")); //wreq.ContentType = "application/json"; wreq.BeginGetResponse((cb) => { HttpWebRequest rq = cb.AsyncState as HttpWebRequest; HttpWebResponse resp = rq.EndGetResponse(cb) as HttpWebResponse; // Exception StreamReader rdr = new StreamReader(resp.GetResponseStream()); string result = rdr.ReadToEnd(); rdr.Close(); }, wreq); EDIT: While perusing SO, I noticed similar posts, like this one Why am I getting ProtocolViolationException when trying to use HttpWebRequest? and this one How do I use HttpWebRequest with GET method EDIT: The WCF 4 end point is 'adapted' from this link http://geekswithblogs.net/michelotti/archive/2010/08/21/restful-wcf-services-with-no-svc-file-and-no-config.aspx. I can use Fiddler's request builder to to construct the proper requests and changing the content type does yield the correct results.

    Read the article

  • json parsing problems

    - by C.
    Hi I have the following Json : "{\"doc\":{\"info\":{\"allowDistribution\":\"true\",\"allowSearch\":\"true\",\"calaisRequestID\":\"67a02f61-7e45-cfc4-1276-e123c5f7422f\",\"externalID\":\"\",\"id\":\"http://id.opencalais.com/dBo1YRiQeqS-kfO-m9UeWA\",\"docId\":\"http://d.opencalais.com/dochash-1/8edabb36-eece-3f67-b187-ab64cd885ecb\",\"document\":\"What type of music do you listen to? How much would you pay for a cd? Do you still buy cds? Do you like Shakira? What genre of music do you listen to?\",\"docTitle\":\"\",\"docDate\":\"2010-03-17 17:40:41.323\",\"externalMetadata\":\"\",\"submitter\":\"\"},\"meta\":{\"contentType\":\"text/raw\",\"emVer\":\"7.1.1103.5\",\"langIdVer\":\"DefaultLangId\",\"processingVer\":\"CalaisJob01\",\"submitionDate\":\"2010-03-17 17:40:41.183\",\"submitterCode\":\"b54c734e-b865-185b-c83a-66e1c66272de\",\"signature\":\"digestalg-1|FXnvwLovOsqVoSPX0JfGvj3tp7s=|cyV2tZWY9OXG1RBO0SuND4kd3Pkvqv0cS2YpsEBQhXDfSV4KoE61sQ==\",\"language\":\"English\",\"messages\":[]}},\"http://d.opencalais.com/dochash-1/8edabb36-eece-3f67-b187-ab64cd885ecb/cat/1\":{\"_typeGroup\":\"topics\",\"category\":\"http://d.opencalais.com/cat/Calais/EntertainmentCulture\",\"classifierName\":\"Calais\",\"categoryName\":\"Entertainment_Culture\",\"score\":1},\"http://d.opencalais.com/dochash-1/8edabb36-eece-3f67-b187-ab64cd885ecb/cat/2\":{\"_typeGroup\":\"topics\",\"category\":\"http://d.opencalais.com/cat/Calais/HumanInterest\",\"classifierName\":\"Calais\",\"categoryName\":\"Human Interest\",\"score\":1},\"http://d.opencalais.com/dochash-1/8edabb36-eece-3f67-b187-ab64cd885ecb/cat/3\":{\"_typeGroup\":\"topics\",\"category\":\"http://d.opencalais.com/cat/Calais/TechnologyInternet\",\"classifierName\":\"Calais\",\"categoryName\":\"Technology_Internet\",\"score\":0.932}}" Can you please tell me why it won't parse this? This is my code: JObject o = JObject.Parse(json); String category = (string)o["doc"]["_typeGroup"]["categoryName"]; It tells me: Object reference not set to an instance of an object. Thanks :)

    Read the article

  • JSON feed to Java Object

    - by mnml
    Hi, I would like to know if there is a webpage/software that can "translate" a Json feed object to a Java object with attributes. For example : { 'firstName': 'John', 'lastName': 'Smith', 'address': { 'streetAddress': '21 2nd Street', 'city': 'New York' } } Would become: class Person { private String firstName; private String lastName; private Address address; public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public Address getAddress() { return address; } public void setFirstName(String firstName) { this.firstName = firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public void setAddress(Address address) { this.address = address; } public String toString() { return String.format("firstName: %s, lastName: %s, address: [%s]", firstName, lastName, address); } } class Address { private String streetAddress; private String city; public String getStreetAddress() { return streetAddress; } public String getCity() { return city; } public void setStreetAddress(String streetAddress) { this.streetAddress = streetAddress; } public void setCity(String city) { this.city = city; } public String toString() { return String.format("streetAddress: %s, city: %s", streetAddress, city); } } I'm not asking that because I'm lazy, but the JSON I would like to parse has quite a lot of attribute.

    Read the article

  • Use queried json data in a function

    - by SztupY
    I have a code similar to this: $.ajax({ success: function(data) { text = ''; for (var i = 0; i< data.length; i++) { text = text + '<a href="#" id="Data_'+ i +'">' + data[i].Name + "</a><br />"; } $("#SomeId").html(text); for (var i = 0; i< data.length; i++) { $("#Data_"+i).click(function() { alert(data[i]); RunFunction(data[i]); return false; }); } } }); This gets an array of some data in json format, then iterates through this array generating a link for each entry. Now I want to add a function for each link that will run a function that does something with this data. The problem is that the data seems to be unavailable after the ajax success function is called (although I thought that they behave like closures). What is the best way to use the queried json data later on? (I think setting it as a global variable would do the job, but I want to avoid that, mainly because this ajax request might be called multiple times) Thanks.

    Read the article

  • increase number of photos from flickr using json

    - by Andrew Welch
    Hi this is my code: Is is possible to get more photos from flickr. What is the standard / default number? $(document).ready(function(){ $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?id=48719970@N07&lang=en-us&format=json&jsoncallback=?", function(data){ $.each(data.items, function(i, item){ var newurl = 'url(' + item.media.m + ')'; $("<div class='images'/>").css('background', newurl).css('backgroundPosition','top center').css('backgroundRepeat','no-repeat').appendTo("#images").wrap("<a target=\"_blank\ href='" + item.link + "'></a>"); }) $("#title").html(data.title); $("#description").html(data.description); $("#link").html("<a href='" + data.link + "' target=\"_blank\">Visit the Viget Inspiration Pool!</a>"); //Notice that the object here is "data" because that information sits outside of "items" in the JSON feed $('.jcycleimagecarousel').cycle({ fx: 'fade', speed: 300, timeout: 3000, next: '#next', prev: '#prev', pause: 1, random: 1 }); }); });

    Read the article

  • adding Json to mutable array resolves in crash

    - by user2957713
    Hello guys I am new to Xcode/iOS developing I trying to add json data to the mutable array , and it results in app crash :( so far here is my code: if(! [defaults objectForKey:@"Person1"]) [defaults setObject:[PersonsFromSearch objectAtIndex:index] forKey:@"Person1"]; else { NSMutableArray *Array = [[NSMutableArray alloc]init]; id object = [defaults objectForKey:@"Person1"]; Array = [object isKindOfClass:[NSArray class]] ? object : @[object]; [Array addObject:[PersonsFromSearch objectAtIndex:index]];//crash here :(( [Array moveObjectFromIndex:[Array count] toIndex:0]; } Crash Dump: * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary addObject:]: unrecognized selector sent to instance 0xbf98dc0' what is wrong here ? can you please help me to resolve this issue Array contains this (Json?) { Address = "\U05d3\U05e8\U05da \U05d4\U05e9\U05dc\U05d5\U05dd 53"; CellPhone = "052-3275381"; EMail = "[email protected]"; EnglishPerson = "Yehuda Konfortes"; FaceBookLink = ""; Fax1 = "03-7330703"; Fax2 = ""; FileNAme = "100050.jpg"; HomeEMail = ""; HomeFax = ""; HomePhone1 = ""; HomePhone2 = ""; PersonID = 100050; PersonName = "\U05d9\U05d4\U05d5\U05d3\U05d4 \U05e7\U05d5\U05e0\U05e4\U05d5\U05e8\U05d8\U05e1"; Phone1 = "03-7330733"; Phone2 = ""; ZipCode = ""; }

    Read the article

  • Best way to transfer an Entity Framework object over the web and back via JSON

    - by AVH
    I've got some MVC code that serializes an EF 3.5 object into an anonymous type for return as a JSON result to an AJAX call on my page. The hurdle I have is that when I send the object back to the server via JSON, (and let the ModelBinder deserialize it for me into my EF type), I have to update it in my Entity Framework context manually. Or at least that's what I'm doing now. It has no EntityKey, so attaching it fails. I end up having to look up the old object and update it property by property. Any ideas around this? Is the solution to pass the EntityKey around with my object? Here's what I have: public void Update(Album album) { using (var db = new BandSitesMasterEntities()) { var albumToUpdate = db.Album.First(x => x.ID == album.ID); albumToUpdate.AlbumTitle = album.AlbumTitle; albumToUpdate.Description = album.Description; albumToUpdate.ReleaseYear = album.ReleaseYear; albumToUpdate.ImageURL = album.ImageURL; albumToUpdate.OtherURL = album.OtherURL; db.SaveChanges(); } } And here's what I'd like to do, or something similar: public void Update(Album album) { using (var db = new BandSitesMasterEntities()) { db.Attach(album) db.SaveChanges(); } }

    Read the article

  • Syntax for documenting JSON structure

    - by Roman A. Taycher
    So I'm trying to document the format of the json returned by an api I am writing against and I'd like to know if there is any popular format for the documentation of json structure. Note I'm not trying to to test or validate anything, I'm just using this for documentation. Also some ways to add comments to non-constants(items always returned w/ the same value) would be nice. This the not totally thought out scheme I'm currently using: Plain names refer to identifiers or types. Some types have type-comment Strings that appear to be constant(always returned for that type of request) strings are "str" Constant Numbers would be just the number Constant null is null Booleans are true/false for constant booleans or Boolean otherwise [a,b,c] are lists with 3 items a,b,c [... ...] is a list of repeating elements of some types/constants/patterns {a:A,b:B,c:c} and {... ...} is the same for a dictionary. example: story := [header,footer] header := {"data":realHeader,"kind":"Listing"} realHeader := {"after": null, "before": null, "children": [{"data": realRealHeader, "kind": "t3"}], "modhash": ""} footer := {"data":AlmostComments,"kind":"Listing"} AlmostComments := {"data": {"after": null, "before": null, "children": comments, "modhash": ""}, "kind": "t1"} comments := [...{"data":comment, "kind":"t1"}...] realRealHeader := {"author": string, "clicked": boolean, "created": int, "created_utc": int, "domain": "code.reddit.com", "downs": int, "hidden": boolean, "id": string-id, "is_self": boolean, "levenshtein": null, "likes": null, "media": null, "media_embed": { }, "name": string-id, "num_comments": int, "over_18": false, "permalink": string-urlLinkToStoryStartingFrom/r, "saved": false, "score": int, "selftext": string, "selftext_html": string-html, "subreddit": string-subredditname, "subreddit_id": string-id, "thumbnail": "", "title": string, "ups": int, "url": "http://code.reddit.com/" } comments := { "author": string, "body": string-body_html-wout-html, "body_html": string-html-formated, "created": int, "created_utc": int, "downs": int, "id": string-id, "levenshtein": null, "likes": null, "link_id": string-id, "name": string-id", "parent_id": string-id, "replies": AlmostComments or null, "subreddit": string-subredditname, "subreddit_id": string-id, "ups": int }

    Read the article

  • How to paginate json data?

    - by Pandiya Chendur
    I used json data and iterated div elements to get my result.... function Iteratejsondata(HfJsonValue) { //var jsonObj = eval('(' + HfJsonValue + ')'); var jsonObj = JSON.parse(HfJsonValue); for (var i = jsonObj.Table.length - 1; i >= 0; i--) { var employee = jsonObj.Table[i]; $('<div class="resultsdiv"><br /><span class="resultName">' + employee.Emp_Name + '</span><span class="resultfields" style="padding-left:100px;">Category&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.Desig_Name + '</span><br /><br /><span id="SalaryBasis" class="resultfields">Salary Basis&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.SalaryBasis + '</span><span class="resultfields" style="padding-left:25px;">Salary&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.FixedSalary + '</span><span style="font-size:110%;font-weight:bolder;padding-left:25px;">Address&nbsp;:</span>&nbsp;<span class="resultfieldvalues">' + employee.Address + '</span></div>').insertAfter('#ResultsDiv'); } $(".resultsdiv:even").addClass("resultseven"); $(".resultsdiv").hover(function() { $(this).addClass("resultshover"); }, function() { $(this).removeClass("resultshover"); }); } I get 22 records in total... Now i want to paginate these divs (i.e) 5 divs per page... Any suggestion...

    Read the article

  • Sending a JSON object to an ASP.NET web service using JQUERY ajax function

    - by uzay95
    I want to create object on the client side of aspx page. And i want to add functions to these javascript classes to make easier the life. Actually i can get and use the objects (derived from the server side classes) which returns from the services. When i wanted to send objects from the client by jquery ajax methods, i couldn't do it :) This is my javascript object: function ClassAndMark(_mark, _lesson){ this.Lesson = _lesson; this.Mark = _mark; } function Student(_name, _surname, _classAndMark){ this.Name = _name; this.SurName = _surname; this.ClassAndMark = _classAndMark; } JSClass.prototype.fSaveToDB(){ $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "/WS/SaveObject.asmx/fSaveToDB"), data: ????????????, dataType: "json" }); } Actually i don't know what should be definition of classes and methods on the Server side but i think: class ClassAndMark{ public string Lesson ; public string Mark ; } class Student{ public string Name ; public string SurName ; public ClassAndMark ClassAndMark ; } Web service is below but again i couldn't get what should be instead of the ???? : [WebMethod()] public void fSaveToDB(???? _obj) { // How can i convert input parameter/parameters // of method in the server side object? }

    Read the article

  • passing string to a AJAX/JSON function

    - by Mikey1980
    I’m having trouble getting a AJAX/JSON function to work correctly. I had this function grabbing value from a drop down box but now I want to use an anchor tag to set it's value. I thought it would be easy to just use the onClick event to pass string to the function I was using for the drop down box but it doesn’t do anything. I’m stumped! Here how I set it up: 1st I add an onClick event… <a href="<?php echo Settings::get('app.webroot'); ?>?view=schedule&action=questions" onmouseout="MM_swapImgRestore();" onmouseover="MM_swapImage('bre','','template/images/schedule/bre_f2.gif',1) onclick="assignCallType('testing')";> 2nd I check main.js.php function assignCallType(type) { alert(type); //just for debugging new Request.JSON({ url: "ajax.php", onSuccess: function(rtndata,txt){ if (rtndata['STATUS'] != 'OK') alert('Error assigning call type to call'); }, onFailure: function (xhr) { alert('Error assigning call type to call'); } }).get({ 'action': 'assignCallType', 'call_type': type }); } 3rd Ajax.php: the variable is back in PHP and values don’t get added to the db, but I also didn’t get the alert from main.js.php if ($_GET['action'] == "assignCallType") { if ($USER->isInsideSales()) { $call_type = $_GET['call_type']; $_SESSION['callinfo']->setCallType($call_type); $_SESSION['callinfo']->save($callid); echo json_encode(array('STATUS'=>'OK')); } else { echo json_encode(array('STATUS'=>'DENIED')); } } Any idea where I am going wrong. The only difference between this and the working drop down is how the function was called, I used onchange="assignCallType(this.value)".

    Read the article

  • Block Cascade Json Serealize?

    - by CrazyJoe
    I have this Class: public class User { public string id{ get; set; } public string name{ get; set; } public string password { get; set; } public string email { get; set; } public bool is_broker { get; set; } public string branch_id { get; set; } public string created_at{get; set;} public string updated_at{get; set;} public UserGroup UserGroup {get;set;} public UserAddress UserAddress { get; set; } public List<UserContact> UserContact {get; set;} public User() { UserGroup = new UserGroup(); UserAddress = new UserAddress(); UserContact = new List<UserContact>(); } } I like to Serealize Only properties , how i block serealization of UserGroup, UserAdress, asn UserContact??? This is my Serealization function: public static string Serealize<T>(T obj) { System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType()); MemoryStream ms = new MemoryStream(); serializer.WriteObject(ms, obj); return Encoding.UTF8.GetString(ms.ToArray(), 0,(int)ms.Length); }

    Read the article

  • I getting undefined using JSON in jQuery why?

    - by YoniGeek
    Im learning some JSON, Im trying to list some data about dogs from twitter...but I can't really present the data...I believe that the error is inside map-method...something I'm missing...thanks for yr help <body> <h1>U almost there!!</h1> <script src="jquery-1.7.1.js"> </script> <script> // PubSub (function( $ ) { var o = $( {} ); $.each({ trigger: 'publish', on: 'subscribe', off: 'unsubscribe' }, function( key, val ) { jQuery[val] = function() { o[key].apply( o, arguments ); }; }); })( jQuery ); $.getJSON('http://search.twitter.com/search.json?q=dogs&callback=?', function( info) { $.publish( 'twitter/info', info ); }); // ... $.subscribe( 'twitter/info', function( e, info ) { $('body').html( $.map( info, function( obj) { // <--- here it's error, something Im missing right? return '<li>' + obj.text + '</li>'; }).join('') ); }); </script> </body> </html>

    Read the article

  • Returning JSON or XML for Exceptions in Jersey

    - by Dominic
    My goal is to have an error bean returned on a 404 with a descriptive message when a object is not found, and return the same MIME type that was requested. I have a look up resource, which will return the specified object in XML or JSON based on the URI (I have setup the com.sun.jersey.config.property.resourceConfigClass servlet parameter so I dont need the Accept header. My JAXBContextResolver has the ErrorBean.class in its list of types, and the correct JAXBContext is returned for this class because I can see in the logs). eg: http://foobar.com/rest/locations/1.json @GET @Path("{id}") @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML}) public Location getCustomer(@PathParam("id") int cId) { //look up location from datastore .... if (location == null) { throw new NotFoundException("Location" + cId + " is not found"); } } And my NotFoundException looks like this: public class NotFoundException extends WebApplicationException { public NotFoundException(String message) { super(Response.status(Response.Status.NOT_FOUND). entity(new ErrorBean( message, Response.Status.NOT_FOUND.getStatusCode() ) .build()); } } The ErrorBean is as follows: @XmlRootElement(name = "error") public class ErrorBean { private String errorMsg; private int errorCode; //no-arg constructor, property constructor, getter and setters ... } However, I'm always getting a 204 No Content response when I try this. I have hacked around, and if I return a string and specify the mime type this works fine: public NotFoundException(String message) { super(Response.status(Response.Status.NOT_FOUND). entity(message).type("text/plain").build()); } I have also tried returning an ErrorBean as a resource. This works fine: {"errorCode":404,"errorMsg":"Location 1 is not found!"}

    Read the article

  • How to format JSON Date?

    - by Mark Struzinski
    I'm taking my first crack at AJAX with jQuery. I'm getting my data onto my page, but I'm having some trouble with the JSON that is returned for Date data types. Basically, I'm getting a string back that looks like this: /Date(1224043200000)/ From a total newbie at JSON - How do I format this to a short date format? Should this be handled somewhere in the jQuery code? I've tried the jQuery.UI.datepicker plugin using $.datepicker.formatDate() wiuth no success. FYI: Here's the solution I came up with using a combination of the answers here: function getMismatch(id) { $.getJSON("Main.aspx?Callback=GetMismatch", { MismatchId: id }, function(result) { $("#AuthMerchId").text(result.AuthorizationMerchantId); $("#SttlMerchId").text(result.SettlementMerchantId); $("#CreateDate").text(formatJSONDate(Date(result.AppendDts))); $("#ExpireDate").text(formatJSONDate(Date(result.ExpiresDts))); $("#LastUpdate").text(formatJSONDate(Date(result.LastUpdateDts))); $("#LastUpdatedBy").text(result.LastUpdateNt); $("#ProcessIn").text(result.ProcessIn); } ); return false; } function formatJSONDate(jsonDate){ var newDate = dateFormat(jsonDate, "mm/dd/yyyy"); return newDate; } This solution got my object from the callback method and displayed the dates on the page properly using the date format library.

    Read the article

  • Getting Response From Jquery JSON

    - by Howdy_McGee
    I'm having trouble getting a response from my php jquery / json / ajax. I keep combining all these different tutorials together but I still can't seem to pull it all together since no one tutorial follow what I'm trying to do. Right now I'm trying to pass two arrays (since there's no easy way to pass associative arrays) to my jquery ajax function and just alert it out. Here's my code: PHP $names = array('john doe', 'jane doe'); $ids = array('123', '223'); $data['names'] = $names; $data['ids'] = $ids; echo json_encode($data); Jquery function getList(){ $.ajax({ type: "GET", url: 'test.php', data: "", complete: function(data){ var test = jQuery.parseJSON(data); alert(test.names[0]); alert("here"); } }, "json"); } getList(); In my html file all I'm really calling is my javascript file for debugging purposes. I know i'm returning an object but I'm getting an error with null values in my names section, and i'm not sure why. What am I missing? My PHP file returns {"names":["john doe","jane doe"],"ids":["123","223"]} It seems to be just ending here Uncaught TypeError: Cannot read property '0' of undefined so my sub0 is killing me.

    Read the article

< Previous Page | 24 25 26 27 28 29 30 31 32 33 34 35  | Next Page >