Search Results

Search found 4865 results on 195 pages for 'json'.

Page 3/195 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • How can I return json from my WCF rest service (.NET 4), using Json.Net, without it being a string,

    - by Samuel Meacham
    The DataContractJsonSerializer is unable to handle many scenarios that Json.Net handles just fine when properly configured (specifically, cycles). A service method can either return a specific object type (in this case a DTO), in which case the DataContractJsonSerializer will be used, or I can have the method return a string, and do the serialization myself with Json.Net. The problem is that when I return a json string as opposed to an object, the json that is sent to the client is wrapped in quotes. Using DataContractJsonSerializer, returning a specific object type, the response is: {"Message":"Hello World"} Using Json.Net to return a json string, the response is: "{\"Message\":\"Hello World\"}" I do not want to have to eval() or JSON.parse() the result on the client, which is what I would have to do if the json comes back as a string, wrapped in quotes. I realize that the behavior is correct; it's just not what I want/need. I need the raw json; the behavior when the service method's return type is an object, not a string. So, how can I have my method return an object type, but not use the DataContractJsonSerializer? How can I tell it to use the Json.Net serializer instead? Or, is there someway to directly write to the response stream? So I can just return the raw json myself? Without the wrapping quotes? Here is my contrived example, for reference: [DataContract] public class SimpleMessage { [DataMember] public string Message { get; set; } } [ServiceContract] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] public class PersonService { // uses DataContractJsonSerializer // returns {"Message":"Hello World"} [WebGet(UriTemplate = "helloObject")] public SimpleMessage SayHelloObject() { return new SimpleMessage("Hello World"); } // uses Json.Net serialization, to return a json string // returns "{\"Message\":\"Hello World\"}" [WebGet(UriTemplate = "helloString")] public string SayHelloString() { SimpleMessage message = new SimpleMessage() { Message = "Hello World" }; string json = JsonConvert.Serialize(message); return json; } // I need a mix of the two. Return an object type, but use the Json.Net serializer. }

    Read the article

  • Deserialize json with json.net c#

    - by 76mel
    Hi, am new to Json so a little green. I have a Rest Based Service that returns a json string; {"treeNode":[{"id":"U-2905","pid":"R","userId":"2905"}, {"id":"U-2905","pid":"R","userId":"2905"}]} I have been playing with the Json.net and trying to Deserialize the string into Objects etc. I wrote an extention method to help. public static T DeserializeFromJSON<T>(this Stream jsonStream, Type objectType) { T result; using (StreamReader reader = new StreamReader(jsonStream)) { JsonSerializer serializer = new JsonSerializer(); try { result = (T)serializer.Deserialize(reader, objectType); } catch (Exception e) { throw; } } return result; } I was expecting an array of treeNode[] objects. But its seems that I can only deserialize correctly if treeNode[] property of another object. public class treeNode { public string id { get; set; } public string pid { get; set; } public string userId { get; set; } } I there a way to to just get an straight array from the deserialization ? Cheers

    Read the article

  • Create JSON From C# using json Library

    Create JSON From C# using json library available at codeplex...Did you know that DotNetSlackers also publishes .net articles written by top known .net Authors? We already have over 80 articles in several categories including Silverlight. Take a look: here.

    Read the article

  • Json.NET - How to serialize a class using custom resolver

    - by Mendy
    I want to serialize this class: public class CarDisplay { public string Name { get; set; } public string Brand { get; set; } public string Year { get; set; } public PictureDisplay[] Pictures { get; set; } } public class PictureDisplay { public int Id { get; set; } public string SecretKey { get; set; } public string AltText { get; set; } } To this Json test: { Name: "Name value", Brand: "Brand value", Year: "Year value", Pictures: ["url1", "url2", "url3"] } Note that each Car have an pictures array with only url string, instead of all the properties that Picture class have. I know that Json.NET have the notion of Custom Resolver, but I don't sure exactly how to use it.

    Read the article

  • Returning control codes as JSON to a jquery ajax json call

    - by Graham
    I want to know if it is possible to return ascii control codes in JSON format from classic ASP to a jQuery ajax call. This is my jQuery call: $.ajax({ url: "/jsontest.asp", type: "POST", cache: false, dataType: "json", complete: function(data) { var o = $.parseJSON(data.responseText.toString()); }, error: function(data1, data2) { alert("There has been an error - please try again"); } }); This is my called page: {"val1":123,"val2","abcdef"} The above works fine, but if I change my called page to include ascii character 31 (1F) like so: {"val1":123,"val2","abc\x1Fdef"} then I get the alert in my error function. Can this be done, and if so, how please. Note: I'm using jQuery 1.7.1 and both IIS 6 and IIS 7 I have tried: \x1f, %1f, and \u001f

    Read the article

  • windows phone deserialization json

    - by user2042227
    I have a weird issue. so I am making a few calls in my app to a webservice, which replies with data. However I am using a token based login system, so the first time the user enters the app I get a token from the webservice to login for that specific user and that token returns only that users details. The problem I am having is when the user changes I need to make the calls again, to get the new user's details, but using visual studio's breakpoint debugging, it shows the new user's token making the call however the problem is when the json is getting deserialized, it is as if it still reads the old data and deserializes that, when I exit my app with the new user it works fine, so its as if it is reading cached values, but I have no idea how to clear it? I am sure the new calls are being made and the problem lies with the deserializing, but I have tried clearing the values before deserializing them again, however nothing works. am I missing something with the json deserializer, how van I clear its cached values? here I make the call and set it not to cache so it makes a new call everytime: client.Headers[HttpRequestHeader.CacheControl] = "no-cache"; var token_details = await client.DownloadStringTaskAsync(uri); and here I deserialize the result, it is at this section the old data gets shown, so the raw json being shown inside "token_details" is correct, only once I deserialize the token_details, it shows the wrong data. deserialized = JsonConvert.DeserializeObject(token_details); and the class I am deserializing into is a simple class nothing special happening here, I have even tried making the constructor so that it clears the values each time it gets called. public class test { public string status { get; set; } public string name{ get; set; } public string birthday{ get; set; } public string errorDes{ get; set; } public test() { status = ""; name= ""; birthday= ""; errorDes= ""; } } uri's before making the calls: {https://whatever.co.za/token/?code=BEBCg==&id=WP7&junk=121edcd5-ad4d-4185-bef0-22a4d27f2d0c} - old call "UBCg==" - old reply {https://whatever.co.za/token/?code=ABCg==&id=WP7&junk=56cc2285-a5b8-401e-be21-fec8259de6dd} - new call "UBCg==" - new response which is the same response as old call as you can see i did attach a new GUID everytime i make the call, but then the new uri is read before making the downloadstringtaskasync method call, but it returns with the old data

    Read the article

  • spring json writes more json then i want

    - by mkoryak
    I am using the json spring view in order to return a simple JSON object from my controller. The problem is that its returning more data then i want. it is returning the validation errors and things inside of my model when all i am doing is this in the controller: Map model = new HashMap() model.put("success", "true"); return new ModelAndView("jsonView", model); If you look at the bottom of this page in the docs it looks like i am getting back data that POST would return. i am not doing a post, i am doing a GET by going directly to the URL with params. How do i get this lib to return just the data in my model?

    Read the article

  • Tidbits of goodness - Podcasts, REST, JSON

    - by jeff.x.davies
    I've been quiet for a while, busy with a variety of projects. I did want to let you all know about a couple of things going on. First, I have been participating in architectural podcasts with Bob Rhubart. If you are interested in hearing these short (about 10 minutes each) recordings where a group of us discuss enterprise architecture and its future, check out http://blogs.oracle.com/archbeat/2010/05/podcast_show_notes_evolving_en.html Next, I have been working on the public sample code for the Oracle Service Bus 11g release. I'm now expanding my samples to include SCA, BPEL and the Oracle Adapters. This is really great experience for me because I have been learning these other tools to a deeper level and this provides insight into developing better solutions. You know the old saying, "If the only tool you have is a hammer, you tend to appraoch every problem as if it were a nail." However, I'm not the only one working on these samples. We have alot of our best and brightest working on sample code for the 11g release. Take a look at https://soasamples.samplecode.oracle.com/ to see all of the samples for SOA Suite 11g A reader wrote to me and asked me about using OSB to return information in JSON format. I don't have a sample posted for this yet, but I am working on getting one packaged up. In the mean time I can tell you that it is dead simple to do in OSB. Use the instructions I gave in an earlier blog entry on creating REST services using OSB, specify Messaging Service as the service type that takes a Text message and returns a Text message. Then have the OSB proxy service return a JSON formatted string (by replacing the contents of the $body variable with the JSON text) and you're done! This approach allows you to use OSB services from within Javascript/AJAX seamlessly. As I get more samples posted to the OTN site, I'll let you know. I have lots of interesting stuff on the way.

    Read the article

  • Retrieving database column using JSON [migrated]

    - by arokia
    I have a database consist of 4 columns (id-symbol-name-contractnumber). All 4 columns with their data are being displayed on the user interface using JSON. There is a function which is responisble to add new column to the database e.g (countrycode). The coulmn is added successfully to the database BUT not able to show the new added coulmn in the user interface. Below is my code that is displaying the columns. Can you help me? table.php $(document).ready(function () { // prepare the data var theme = getDemoTheme(); var source = { datatype: "json", datafields: [ { name: 'id' }, { name: 'symbol' }, { name: 'name' }, { name: 'contractnumber' } ], url: 'data.php', filter: function() { // update the grid and send a request to the server. $("#jqxgrid").jqxGrid('updatebounddata', 'filter'); }, cache: false }; var dataAdapter = new $.jqx.dataAdapter(source); // initialize jqxGrid $("#jqxgrid").jqxGrid( { source: dataAdapter, width: 670, theme: theme, showfilterrow: true, filterable: true, columns: [ { text: 'id', datafield: 'id', width: 200 }, { text: 'symbol', datafield: 'symbol', width: 200 }, { text: 'name', datafield: 'name', width: 100 }, { text: 'contractnumber', filtertype: 'list', datafield: 'contractnumber' } ] }); }); data.php <?php #Include the db.php file include('db.php'); $query = "SELECT * FROM pricelist"; $result = mysql_query($query) or die("SQL Error 1: " . mysql_error()); $orders = array(); // get data and store in a json array while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $pricelist[] = array( 'id' => $row['id'], 'symbol' => $row['symbol'], 'name' => $row['name'], 'contractnumber' => $row['contractnumber'] ); } echo json_encode($pricelist); ?>

    Read the article

  • High-level strategy for distinguishing a regular string from invalid JSON (ie. JSON-like string detection)

    - by Jonline
    Disclaimer On Absence of Code: I have no code to post because I haven't started writing; was looking for more theoretical guidance as I doubt I'll have trouble coding it but am pretty befuddled on what approach(es) would yield best results. I'm not seeking any code, either, though; just direction. Dilemma I'm toying with adding a "magic method"-style feature to a UI I'm building for a client, and it would require intelligently detecting whether or not a string was meant to be JSON as against a simple string. I had considered these general ideas: Look for a sort of arbitrarily-determined acceptable ratio of the frequency of JSON-like syntax (ie. regex to find strings separated by colons; look for colons between curly-braces, etc.) to the number of quote-encapsulated strings + nulls, bools and ints/floats. But the smaller the data set, the more fickle this would get look for key identifiers like opening and closing curly braces... not sure if there even are more easy identifiers, and this doesn't appeal anyway because it's so prescriptive about the kinds of mistakes it could find try incrementally parsing chunks, as those between curly braces, and seeing what proportion of these fractional statements turn out to be valid JSON; this seems like it would suffer less than (1) from smaller datasets, but would probably be much more processing-intensive, and very susceptible to a missing or inverted brace Just curious if the computational folks or algorithm pros out there had any approaches in mind that my semantics-oriented brain might have missed. PS: It occurs to me that natural language processing, about which I am totally ignorant, might be a cool approach; but, if NLP is a good strategy here, it sort of doesn't matter because I have zero experience with it and don't have time to learn & then implement/ this feature isn't worth it to the client.

    Read the article

  • JSON posting, am i pushing JSON too far?

    - by joe90
    Im just wondering if I am pushing JSON too far? and if anyone has hit this before? I have a xml file: <?xml version="1.0" encoding="UTF-8"?> <customermodel:Customer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:customermodel="http://customermodel" xmlns:personal="http://customermodel/personal" id="1" age="1" name="Joe"> <bankAccounts xsi:type="customermodel:BankAccount" accountNo="10" bankName="HSBC" testBoolean="true" testDate="2006-10-23" testDateTime="2006-10-23T22:15:01+08:00" testDecimal="20.2" testTime="22:15:01+08:00"> <count>0</count> <bankAddressLine>HSBC</bankAddressLine> <bankAddressLine>London</bankAddressLine> <bankAddressLine>31 florence</bankAddressLine> <bankAddressLine>Swindon</bankAddressLine> </bankAccounts> </customermodel:Customer> Which contains elements and attributes.... Which when i convert to JSON gives me: {"customermodel:Customer":{"id":"1","name":"Joe","age":"1","xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","bankAccounts":{"testDate":"2006-10-23","testDecimal":"20.2","count":"0","testDateTime":"2006-10-23T22:15:01+08:00","bankAddressLine":["HSBC","London","31 florence","Swindon"],"testBoolean":"true","bankName":"HSBC","accountNo":"10","xsi:type":"customermodel:BankAccount","testTime":"22:15:01+08:00"},"xmlns:personal":"http://customermodel/personal","xmlns:customermodel":"http://customermodel"}} So then i send this too the client.. which coverts to a js object (or whatever) edits some values (the elements) and then sends it back to the server. So i get the JSON string, and convert this back into XML: <customermodel:Customer> <id>1</id> <age>1</age> <name>Joe</name> <xmlns:xsi>http://www.w3.org/2001/XMLSchema-instance</xmlns:xsi> <bankAccounts> <testDate>2006-10-23</testDate> <testDecimal>20.2</testDecimal> <testDateTime>2006-10-23T22:15:01+08:00</testDateTime> <count>0</count> <bankAddressLine>HSBC</bankAddressLine> <bankAddressLine>London</bankAddressLine> <bankAddressLine>31 florence</bankAddressLine> <bankAddressLine>Swindon</bankAddressLine> <accountNo>10</accountNo> <bankName>HSBC</bankName> <testBoolean>true</testBoolean> <xsi:type>customermodel:BankAccount</xsi:type> <testTime>22:15:01+08:00</testTime> </bankAccounts> <xmlns:personal>http://customermodel/personal</xmlns:personal> <xmlns:customermodel>http://customermodel</xmlns:customermodel> </customermodel:Customer> And there is the problem, is doesn't seem to know the difference between elements/attributes so i can not check against a XSD to check this is now valid? Is there a solution to this? I cannot be the first to hit this problem?

    Read the article

  • How to decode a JSON String

    - by ilnur777
    Hi, everybody! Could I ask you to help me to decode this JSON code: $json = '{"inbox":[{"from":"55512351","date":"29\/03\/2010","time":"21:24:10","utcOffsetSeconds":3600,"recipients":[{"address":"55512351","name":"55512351","deliveryStatus":"notRequested"}],"body":"This is message text."},{"from":"55512351","date":"29\/03\/2010","time":"21:24:12","utcOffsetSeconds":3600,"recipients":[{"address":"55512351","name":"55512351","deliveryStatus":"notRequested"}],"body":"This is message text."},{"from":"55512351","date":"29\/03\/2010","time":"21:24:13","utcOffsetSeconds":3600,"recipients":[{"address":"55512351","name":"55512351","deliveryStatus":"notRequested"}],"body":"This is message text."},{"from":"55512351","date":"29\/03\/2010","time":"21:24:13","utcOffsetSeconds":3600,"recipients":[{"address":"55512351","name":"55512351","deliveryStatus":"notRequested"}],"body":"This is message text."}]}'; I would like to organize above structure to this: Note 1: Folder: inbox From (from): ... Date (date): ... Time (time): ... utcOffsetSeconds: ... Recepient (address): ... Recepient (name): ... Status (deliveryStatus): ... Text (body): ... Note 2: ... Thank you in advance!

    Read the article

  • is this valid json array using php

    - by Rich
    Hello, I need to convert some code done by someone else, to work in my mvc model It is using some functions like EOD that I don't understand. Does that still work in a class? Primarely, my question focusus on the json output. The old code does not use the php json_encode function, but outputs it directly like this ?> { "username": "<?php echo $_SESSION['username'];?>", "items": [ <?php echo $items;?> ] } <?php I would do it like this, but I need to be sure it's right for the items part header('Content-type: application/json'); $output = array("username"=> isset( $_SESSION['username'] ) ? $_SESSION['username'] : "?", "items"=>$items ); $this->content = json_encode($output); This is some background on how the $items is made. An item is stored like this: $_SESSION['chatHistory'][$_POST['to']] .= <<<EOD { "s": "1", "f": "{$to}", "m": "{$messagesan}" }, EOD; and it is put in the $items variable like this $items = ''; if ( !empty($_SESSION['openChatBoxes'] ) ) { foreach ( $_SESSION['openChatBoxes'] as $chatbox => $void ) { $items .= $this->chatBoxSession($chatbox); } } //The chatBoxSession() function takes an item from the $_SESSION['chatHistory'] array and returns it. I hope this was somewhat clear enough? The php manual warns that in some cases you don't get an array output, instead you get an object. So, with the EOD syntax, I am not really sure. It could save me some time if I know some things are doing what they supposed too, and giving the right output. thanks, Richard

    Read the article

  • PHP cURL JSON Decode (X-AUTH Header)

    - by TheCyX
    <?php // Show Profile $curl = curl_init(); curl_setopt ($curl, CURLOPT_URL, "https://example/api"); curl_setopt ($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt ($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC ) ; curl_setopt ($curl, CURLOPT_HTTPHEADER, array('X-AUTH: 123456789')); $projects = curl_exec($curl); // This is empty? echo $projects; //Decode $phpArray = json_decode($projects); print_r($phpArray); foreach ($phpArray as $key => $value) { // Line 17, sure its empty, but why? echo "<p>$key | $value</p>"; } ?> Warning: Invalid argument supplied for foreach() in /html/api.php on line 17 The API needs this authentification: $ curl -i -H "X-AUTH: 123456789" https://example/api JSON File: {"id":"123456","hostId":null,"Nickname":"thecyx","DisplayName":"thecyx","AppDisplayName":"thecyx","Score":"300","Account":"Full"} The $project variable is empty. If I'm posting the API Url in the Broswer its working. And, if possible, what's the correct way to get the JSON Data e.g. [Nickname],[Score]?

    Read the article

  • PHP Json Encoding w/ quote escaping in 5.2?

    - by NickAldwin
    I'm playing with the flickr api and php. I want to pass some information from PHP to Javascript through Ajax. I have the following code: json_encode($pics); which results in the following example JSON string: [{"id":"4363603591","title":"blue, white and red...another seattle view","date_faved":"1266379499"},{"id":"4004908219","title":"\u201cI just told you my dreams and you made me see that I could walk into the sun and I could still be me and now I can't deny nothing lasts forever.\u201d","date_faved":"1259987670"}] Javascript has problems with this, however, due to the unescaped single-quote in the second item ("can't deny"). I want to use the function json_encode with the options parameter to make it strip the quotes, but that's only available in PHP 5.3, and I'm running 5.2 (not my server). Is there a fast way to run through the entire array and escape everything before encoding it in Json? I looked for a way to do this, but it all seems to deal with encoding it as the data is generated, something I cannot do as I'm not the one generating the data. If it helps, I'm currently using the following javascript after the ajax request: var photos = eval('(' + resptxt + ')');

    Read the article

  • Parsing JSON to XML using net.sf.json (java)

    - by Castanho
    Hi guys, I'm parsing a generic JSON to a XML using net.sf.json. (I'm not using POJO Obj in the conversion) When dealing with vectors I'm receiving: <root> <entry> <Id>1</accountId> <Items> <e> <cost>0.1</cost> <debit>0.1</debit> </e> <e> <cost>0.1</cost> <debit>0.1</debit> </e> </Items> </entry> </root> When the correct for my point of view should be: <root> <entry> <accountId>1</accountId> <Items> <cost>0.1</cost> <debit>0.1</debit> </Items> <Items> <cost>0.2</cost> <debit>0.2</debit> </Items> </entry> </root> Do anyone have used this lib and could help me? Any tips could help! Thanks in advance

    Read the article

  • Converting a generic list into JSON string and then handling it in java script

    - by Jalpesh P. Vadgama
    We all know that JSON (JavaScript Object Notification) is very useful in case of manipulating string on client side with java script and its performance is very good over browsers so let’s create a simple example where convert a Generic List then we will convert this list into JSON string and then we will call this web service from java script and will handle in java script. To do this we need a info class(Type) and for that class we are going to create generic list. Here is code for that I have created simple class with two properties UserId and UserName public class UserInfo { public int UserId { get; set; } public string UserName { get; set; } } Now Let’s create a web service and web method will create a class and then we will convert this with in JSON string with JavaScriptSerializer class. Here is web service class. using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; namespace Experiment.WebService { /// <summary> /// Summary description for WsApplicationUser /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService] public class WsApplicationUser : System.Web.Services.WebService { [WebMethod] public string GetUserList() { List<UserInfo> userList = new List<UserInfo>(); for (int i = 1; i <= 5; i++) { UserInfo userInfo = new UserInfo(); userInfo.UserId = i; userInfo.UserName = string.Format("{0}{1}", "J", i.ToString()); userList.Add(userInfo); } System.Web.Script.Serialization.JavaScriptSerializer jSearializer = new System.Web.Script.Serialization.JavaScriptSerializer(); return jSearializer.Serialize(userList); } } } Note: Here you must have this attribute here in web service class ‘[System.Web.Script.Services.ScriptService]’ as this attribute will enable web service to call from client side. Now we have created a web service class let’s create a java script function ‘GetUserList’ which will call web service from JavaScript like following function GetUserList() { Experiment.WebService.WsApplicationUser.GetUserList(ReuqestCompleteCallback, RequestFailedCallback); } After as you can see we have inserted two call back function ReuqestCompleteCallback and RequestFailedCallback which handle errors and result from web service. ReuqestCompleteCallback will handle result of web service and if and error comes then RequestFailedCallback will print the error. Following is code for both function. function ReuqestCompleteCallback(result) { result = eval(result); var divResult = document.getElementById("divUserList"); CreateUserListTable(result); } function RequestFailedCallback(error) { var stackTrace = error.get_stackTrace(); var message = error.get_message(); var statusCode = error.get_statusCode(); var exceptionType = error.get_exceptionType(); var timedout = error.get_timedOut(); // Display the error. var divResult = document.getElementById("divUserList"); divResult.innerHTML = "Stack Trace: " + stackTrace + "<br/>" + "Service Error: " + message + "<br/>" + "Status Code: " + statusCode + "<br/>" + "Exception Type: " + exceptionType + "<br/>" + "Timedout: " + timedout; } Here in above there is a function called you can see that we have use ‘eval’ function which parse string in enumerable form. Then we are calling a function call ‘CreateUserListTable’ which will create a table string and paste string in the a div. Here is code for that function. function CreateUserListTable(userList) { var tablestring = '<table ><tr><td>UsreID</td><td>UserName</td></tr>'; for (var i = 0, len = userList.length; i < len; ++i) { tablestring=tablestring + "<tr>"; tablestring=tablestring + "<td>" + userList[i].UserId + "</td>"; tablestring=tablestring + "<td>" + userList[i].UserName + "</td>"; tablestring=tablestring + "</tr>"; } tablestring = tablestring + "</table>"; var divResult = document.getElementById("divUserList"); divResult.innerHTML = tablestring; } Now let’s create div which will have all html that is generated from this function. Here is code of my web page. We also need to add a script reference to enable web service from client side. Here is all HTML code we have. <form id="form1" runat="server"> <asp:ScriptManager ID="myScirptManger" runat="Server"> <Services> <asp:ServiceReference Path="~/WebService/WsApplicationUser.asmx" /> </Services> </asp:ScriptManager> <div id="divUserList"> </div> </form> Now as we have not defined where we are going to call ‘GetUserList’ function so let’s call this function on windows onload event of javascript like following. window.onload=GetUserList(); That’s it. Now let’s run it on browser to see whether it’s work or not and here is the output in browser as expected. That’s it. This was very basic example but you can crate your own JavaScript enabled grid from this and you can see possibilities are unlimited here. Stay tuned for more.. Happy programming.. Technorati Tags: JSON,Javascript,ASP.NET,WebService

    Read the article

  • JSON Search and remove in php?

    - by moogeek
    Hello! I have a session variable $_SESSION["animals"] containing a deep json object with values: $_SESSION["animals"]='{ "0":{"kind":"mammal","name":"Pussy the Cat","weight":"12kg","age":"5"}, "1":{"kind":"mammal","name":"Roxy the Dog","weight":"25kg","age":"8"}, "2":{"kind":"fish","name":"Piranha the Fish","weight":"1kg","age":"1"}, "3":{"kind":"bird","name":"Einstein the Parrot","weight":"0.5kg","age":"4"}, }'; For example, I want to find the line with "Piranha the Fish" and then remove it (and json_encode it again as it was). How to do this? I guess i need to search in json_decode($_SESSION["animals"],true) resulting array and find the parent key to remove but i'm stucked anyways.

    Read the article

  • How to check if JavaScript object is JSON

    - by Wei Hao
    I have a nested JSON object that I need to loop through, and the value of each key could be a String, JSON array or another JSON object. Depending on the type of object, I need to carry out different operations. Is there any way I can check the type of the object to see if it is a String, JSON object or JSON array? I tried using typeof and instanceof but both didn't seem to work, as typeof will return an object for both JSON object and array, and instanceof gives an error when I do obj instanceof JSON. To be more specific, after parsing the JSON into a JS object, is there any way I can check if it is a normal string, or an object with keys and values (from a JSON object), or an array (from a JSON array)? For example: JSON var data = {"hi": {"hello": ["hi1","hi2"] }, "hey":"words" } JavaScript var jsonObj = JSON.parse(data); var level1 = jsonObj.hi; var text = jsonObj.hey; var arr = level1.hello; //how to check if level1 was formerly a JSON object? //how to check if arr was formerly a JSON array? //how to check if text is a string?

    Read the article

  • Easy to use JSON Web Service Hosts?

    - by Serguei Fedorov
    I saw this being used by someone in a college class once and cannot find anything that is analogous to it. I am not sure if this is the right place to ask about something like this, but hopefully I can get some direction. I want to write an app which uses web services that can obtain and push data back to the client apps. Right now I am gathering up the design and documentation of this app. Not having to code the web service myself would reduce development time by a lot; instead using an easy to setup web service that will be easy to setup and manage. Either XML based on JSON based is totally fine; though I would prefer JSON for its reduced overhead. Like I said I have seen this demonstrated before; you define the data structure to be stored and how it is treated. I cannot find the person who demonstrated this; hopefully maybe someone can suggest something? The service he used was free with a limited amount of requests allowed. EDIT: He was using an online service to do this not a script which is installed onto an existing web hosting account. Thank you!

    Read the article

  • Domain model integration using JSON capable DTOs

    - by g-makulik
    I'm a bit confused about architectural choices for the java/web-applications world. The background is I have a system with certain hardware components (that introduce system immanent active behavior) and a configuration database for system meta and HW-components configuration data (these are even usually self contained, since the HW-components persist configuration data anyway). For realization of the configuration/status data exchange protocol with the HW-components we have chosen the Google Protobuf format, which works well for the directly wired communication with these components. Now we want to develop an abstract model (domain model) for those HW-components and I have the feeling that a plain Java class model would fit best for this (c++ implementation seems to have too much implementation/integration overhead with viable language-bridge interfaces). Google Protobuf message definitions could still serve well to describe DTO objects used to interact with a domain model API. But integrating Google Protobuf messages client side for e.g. data binding in the current view doesn't seem to be a good choice. I'm thinking about some extra serialization features, e.g. for JSON based data exchange with the views/controllers. Most lightweight solutions seem to involve a python based presentation layer using JSON based data transfer (I'm at least not sure to be fully informed about this). Is there some lightweight (applicable for a limited ARM Linux platform) framework available, supporting such architecture to realize a web-application?

    Read the article

  • JScript JSON Object Check

    - by George
    I'm trying to check if json[0]['DATA']['name'][0]['DATA']['first_0'] exists or not when in some instances json[0]['DATA']['name'] contains nothing. I can check json[0]['DATA']['name'] using if (json[0]['DATA']['name'] == '') { // DOES NOT EXIST } however if (json[0]['DATA']['name'][0]['DATA']['first_0'] == '' || json[0]['DATA']['name'][0]['DATA']['first_0'] == 'undefined') { // DOES NOT EXIST } returns json[0]['DATA']['name'][0]['DATA'] is null or not an object. I understand this is because the array 'name' doesn't contain anything in this case, but in other cases first_0 does exist and json[0]['DATA']['name'] does return a value. Is there a way that I can check json[0]['DATA']['name'][0]['DATA']['first_0'] directly without having to do the following? if (json[0]['DATA']['name'] == '') { if (json[0]['DATA']['name'][0]['DATA']['first_0'] != 'undefined') { // OBJECT EXISTS } }

    Read the article

  • Get specifc value from JSon string using JSon.Net

    - by dean nolan
    I am trying to get a value from a JSon formatted string. It was to get album info from a website called Freebase. My result is like this: { "a0": { "code": "/api/status/error", "messages": [ { "code": "/api/status/error/mql/result", "info": { "count": 20, "result": [ { "album": [ { "name": "Definitely Maybe", "release_date": "1994-08-30" } ], "artist": "Oasis", "name": "Live Forever", "type": "/music/track" }, { "album": [ { "name": "Most Wanted Rock 1", "release_date": null } ], "artist": "Oasis", "name": "Live Forever", "type": "/music/track" }, { "album": [ { "name": "Alternative 90s", "release_date": null } ], "artist": "Oasis", "name": "Live Forever", "type": "/music/track" }, { "album": [ { "name": "Live Forever: Best of Britpop", "release_date": "2003-03-03" } ], "artist": "Oasis", "name": "Live Forever", "type": "/music/track" }, { "album": [ { "name": "The Best... In the World... Ever! Volume 5", "release_date": "1997-03-31" } ], "artist": "Oasis", "name": "Live Forever", "type": "/music/track" }, { "album": [ { "name": "Live 4 Ever", "release_date": "1998-06-29" } ], "artist": "Oasis", "name": "Live Forever", "type": "/music/track" }, { "album": [ { "name": "De Afrekening, Volume 8", "release_date": "1994" } ], "artist": "Oasis", "name": "Live Forever", "type": "/music/track" }, { "album": [ { "name": "Now That's What I Call Music! 33", "release_date": null } ], "artist": "Oasis", "name": "Live Forever", "type": "/music/track" }, { "album": [ { "name": "Q: Anthems", "release_date": null } ], "artist": "Oasis", "name": "Live Forever", "type": "/music/track" }, { "album": [ { "name": "The Best Anthems... Ever! Volume 2", "release_date": null } ], "artist": "Oasis", "name": "Live Forever", "type": "/music/track" }, { "album": [ { "name": "1995 Mercury Music Prize: Ten Albums of the Year", "release_date": null } ], "artist": "Oasis", "name": "Live Forever", "type": "/music/track" }, { "album": [ { "name": "Now That's What I Call Music! 1994", "release_date": null } ], "artist": "Oasis", "name": "Live Forever", "type": "/music/track" }, { "album": [ { "name": "Indie Top 20, Volume 21", "release_date": "1995" } ], "artist": "Oasis", "name": "Live Forever", "type": "/music/track" }, { "album": [ { "name": "Dad Rocks!", "release_date": "2006-06-05" } ], "artist": "Oasis", "name": "Live Forever", "type": "/music/track" }, { "album": [ { "name": "Untitled", "release_date": null } ], "artist": "Oasis", "name": "Live Forever", "type": "/music/track" }, { "album": [ { "name": "The Greatest Hits of 1994", "release_date": "1994-10" } ], "artist": "Oasis", "name": "Live Forever", "type": "/music/track" }, { "album": [ { "name": "Top of the Pops 2", "release_date": "2000-03-27" } ], "artist": "Oasis", "name": "Live Forever", "type": "/music/track" }, { "album": [ { "name": "Q: Anthems (disc 1)", "release_date": null } ], "artist": "Oasis", "name": "Live Forever", "type": "/music/track" }, { "album": [ { "name": "Jamie Oliver's Cookin'", "release_date": "2001" } ], "artist": "Oasis", "name": "Live Forever", "type": "/music/track" }, { "album": [ { "name": "Killer Buzz", "release_date": "2001" } ], "artist": "Oasis", "name": "Live Forever", "type": "/music/track" } ] }, "message": "Unique query may have at most one result. Got 20", "path": "", "query": { "album": [ { "name": null, "release_date": null, "sort": "release_date" } ], "artist": "Oasis", "error_inside": ".", "name": "Live Forever", "type": "/music/track" } } ] }, "code": "/api/status/ok", "status": "200 OK", "transaction_id": "cache;cache04.p01.sjc1:8101;2010-03-30T18:04:20Z;0035" } I am looking to get the first album title, Definitely Maybe, from this list. I have tried parsing the string like this: JObject o = JObject.Parse(jsonString); string album = (string)o[""]; But no matter what I have tried I don't know what to put in those quotes. How would I get this specific value or be able to search for it? Thanks

    Read the article

  • JSON error Caused by: java.lang.NullPointerException

    - by user3821853
    im trying to make a register page on android using JSON. everytime i press register button on avd, i get an error "unfortunately database has stopped". i have a error on my logcat that i cannot understand. this my code. please someone help me. this my register.java import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class Register extends Activity implements OnClickListener{ private EditText user, pass; private Button mRegister; // Progress Dialog private ProgressDialog pDialog; // JSON parser class JSONParser jsonParser = new JSONParser(); //php register script //localhost : //testing on your device //put your local ip instead, on windows, run CMD > ipconfig //or in mac's terminal type ifconfig and look for the ip under en0 or en1 // private static final String REGISTER_URL = "http://xxx.xxx.x.x:1234/webservice/register.php"; //testing on Emulator: private static final String REGISTER_URL = "http://10.0.2.2:1234/webservice/register.php"; //testing from a real server: //private static final String REGISTER_URL = "http://www.mybringback.com/webservice/register.php"; //ids private static final String TAG_SUCCESS = "success"; private static final String TAG_MESSAGE = "message"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.register); user = (EditText)findViewById(R.id.username); pass = (EditText)findViewById(R.id.password); mRegister = (Button)findViewById(R.id.register); mRegister.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub new CreateUser().execute(); } class CreateUser extends AsyncTask<String, String, String> { @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(Register.this); pDialog.setMessage("Creating User..."); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected String doInBackground(String... args) { // TODO Auto-generated method stub // Check for success tag int success; String username = user.getText().toString(); String password = pass.getText().toString(); try { // Building Parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("username", username)); params.add(new BasicNameValuePair("password", password)); Log.d("request!", "starting"); //Posting user data to script JSONObject json = jsonParser.makeHttpRequest( REGISTER_URL, "POST", params); // full json response Log.d("Registering attempt", json.toString()); // json success element success = json.getInt(TAG_SUCCESS); if (success == 1) { Log.d("User Created!", json.toString()); finish(); return json.getString(TAG_MESSAGE); }else{ Log.d("Registering Failure!", json.getString(TAG_MESSAGE)); return json.getString(TAG_MESSAGE); } } catch (JSONException e) { e.printStackTrace(); } return null; } protected void onPostExecute(String file_url) { // dismiss the dialog once product deleted pDialog.dismiss(); if (file_url != null){ Toast.makeText(Register.this, file_url, Toast.LENGTH_LONG).show(); } } } } this is JSONparser.java import android.util.Log; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URLEncodedUtils; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.List; public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; // constructor public JSONParser() { } public JSONObject getJSONFromUrl(final String url) { // Making HTTP request try { // Construct the client and the HTTP request. DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); // Execute the POST request and store the response locally. HttpResponse httpResponse = httpClient.execute(httpPost); // Extract data from the response. HttpEntity httpEntity = httpResponse.getEntity(); // Open an inputStream with the data content. is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { // Create a BufferedReader to parse through the inputStream. BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); // Declare a string builder to help with the parsing. StringBuilder sb = new StringBuilder(); // Declare a string to store the JSON object data in string form. String line = null; // Build the string until null. while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } // Close the input stream. is.close(); // Convert the string builder data to an actual string. json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // Try to parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // Return the JSON Object. return jObj; } // function get json from url // by making HTTP POST or GET mehtod public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) { // Making HTTP request try { // check for request method if(method == "POST"){ // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); }else if(method == "GET"){ // request method is GET DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } and this my error 08-18 23:40:02.381 2000-2018/com.example.blackcustomzier.database E/Buffer Error? Error converting result java.lang.NullPointerException: lock == null 08-18 23:40:02.381 2000-2018/com.example.blackcustomzier.database E/JSON Parser? Error parsing data org.json.JSONException: End of input at character 0 of 08-18 23:40:02.391 2000-2018/com.example.blackcustomzier.database W/dalvikvm? threadid=15: thread exiting with uncaught exception (group=0xb0f37648) 08-18 23:40:02.391 2000-2018/com.example.blackcustomzier.database E/AndroidRuntime? FATAL EXCEPTION: AsyncTask #4 java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:299) at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352) at java.util.concurrent.FutureTask.setException(FutureTask.java:219) at java.util.concurrent.FutureTask.run(FutureTask.java:239) at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573) at java.lang.Thread.run(Thread.java:841) Caused by: java.lang.NullPointerException at com.example.blackcustomzier.database.Register$CreateUser.doInBackground(Register.java:108) at com.example.blackcustomzier.database.Register$CreateUser.doInBackground(Register.java:74) at android.os.AsyncTask$2.call(AsyncTask.java:287) at java.util.concurrent.FutureTask.run(FutureTask.java:234)             at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)             at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)             at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)             at java.lang.Thread.run(Thread.java:841) 08-18 23:40:02.501 2000-2000/com.example.blackcustomzier.database W/EGL_emulation? eglSurfaceAttrib not implemented 08-18 23:40:02.591 2000-2000/com.example.blackcustomzier.database W/EGL_emulation? eglSurfaceAttrib not implemented 08-18 23:40:02.981 2000-2000/com.example.blackcustomzier.database E/WindowManager? Activity com.example.blackcustomzier.database.Register has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b1294c60 V.E..... R......D 0,0-1026,288} that was originally added here android.view.WindowLeaked: Activity com.example.blackcustomzier.database.Register has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{b1294c60 V.E..... R......D 0,0-1026,288} that was originally added here at android.view.ViewRootImpl.<init>(ViewRootImpl.java:345) at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:239) at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69) at android.app.Dialog.show(Dialog.java:281) at com.example.blackcustomzier.database.Register$CreateUser.onPreExecute(Register.java:85) at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586) at android.os.AsyncTask.execute(AsyncTask.java:534) at com.example.blackcustomzier.database.Register.onClick(Register.java:70) at android.view.View.performClick(View.java:4240) at android.view.View.onKeyUp(View.java:7928) at android.widget.TextView.onKeyUp(TextView.java:5606) at android.view.KeyEvent.dispatch(KeyEvent.java:2647) at android.view.View.dispatchKeyEvent(View.java:7343) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1393) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1393) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1393) at android.view.ViewGroup.dispatchKeyEvent(ViewGroup.java:1393) at com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchKeyEvent(PhoneWindow.java:1933) at com.android.internal.policy.impl.PhoneWindow.superDispatchKeyEvent(PhoneWindow.java:1408) at android.app.Activity.dispatchKeyEvent(Activity.java:2384) at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1860) at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:3791) at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3774) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398) at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3483) at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406) at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3540) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398) at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3406) at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3379) at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3429) at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3398) at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3516) at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:3666) at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:1982) at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:1698) at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1689) at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:1959) at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141) at android.os.MessageQueue.nativePollOnce(Native Method) at android.os.MessageQueue.next(MessageQueue.java:132) at android.os.Looper.loop(Looper.java:124) at android.app.ActivityThread.main(ActivityThread.java:5103) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:525) at com.android.internal.os.ZygoteInit$MethodAndArgsCal please help me to solve this thx

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >