Search Results

Search found 5517 results on 221 pages for 'json decode'.

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

  • How to use json object notation to retrieve dbpedia json data

    - by Margi
    In my php code, I am retrieving json data as below. <?php $url = "http://dbpedia.org/data/Los_Angeles.json"; $data = file_get_contents($url); echo $data; ?> The javascript code consumes this json data returned from php and gets the json object as below. var doc = eval('(' + request.responseText + ')'); How to retrieve the following json data using dot notations. The keys contain URLs. "http://dbpedia.org/ontology/populationTotal" : [ { "type" : "literal", "value" : 3792621 , "datatype" : "http://www.w3.org/2001/XMLSchema#integer" } ] , "http://dbpedia.org/ontology/PopulatedPlace/areaTotal" : [ { "type" : "literal", "value" : "1301.9688931491348" , "datatype" : "http://dbpedia.org/datatype/squareKilometre" }

    Read the article

  • Encode JSON data into another JSON object

    - by jburns20
    I have a JSON string that I would like to include as a value in a larger JSON object that I am creating from an array. How can I create the larger JSON object without php escaping the string, and without having to decode the previously encoded string? For example, if my JSON string is: $encoded_already = '{"encoded_key": "encoded_value"}'; And I would like to include it in my array and json_encode() it: $new_array = array( "some_other_key" => $some_value, "premade_data" => $encoded_already ); $output = json_encode($new_array); but I want to have the $encoded_already string be included as actual JSON, not just an escaped string.

    Read the article

  • How to get JSON code into MYSQL database?

    - by the_boy_za
    I've created this form with a jQuery autocomplete function. The selected brand from the autocomplete list needs to get sent to a PHP file using $.ajax function. My code doesn't seem to work but i can't find the error. I don't know why the data isn't getting inserted into MYSQL database. Here is my code: JQUERY: $(document).ready(function() { $("#autocomplete").autocomplete({ minLength: 2 }); $("#autocomplete").autocomplete({ source: ["Adidas", "Airforce", "Alpha Industries", "Asics", "Bikkemberg", "Birkenstock", "Bjorn Borg", "Brunotti", "Calvin Klein", "Cars Jeans", "Chanel", "Chasin", "Diesel", "Dior", "DKNY", "Dolce & Gabbana"] }); $("#add-brand").click(function() { var merk = $("#autocomplete").val(); $("#selected-brands").append(" <a class=\"deletemerk\" href=\"#\">" + merk + "</a>"); //Add your parameters here var param = JSON.stringify({ Brand: merk }); $.ajax({ type: "POST", async: true, url: "scripttohandlejson.php", contentType: "application/json", data: param, dataType: "json", success: function (good){ //handle success alert(good) }, failure: function (bad){ //handle any errors alert(bad) } }); return false; }); }); PHP FILE: scripttohandlejson.php <?PHP $getcontent = json_decode($json, true); $getcontent->{'Brand'}; $vraag ="INSERT INTO kijken (merk) VALUES ='$getcontent' "; $voerin = mysql_query($vraag) or die("couldnt put into db"); <?

    Read the article

  • struts2-json-plugin not retrieving json data from action class for Struts-JQuery-Plugin grid

    - by thebravedave
    Hello, Im having an issue getting json working with the struts-jquery-plugin-2.1.0 I have included the struts2-json-plugin-2.1.8.1 in my classpath as well. Im sure that I have my struts-jquery-plugin configured correctly because the grid loads, but doesnt load the data its supposed to get from the action class that has been json'ized. The documentation with the json plugin and the struts-jquery plugin leaves ALOT of gaps that I cant even find with examples/tutorials, so I come to the community at stackoverflow. My action class has a property called gridModel thats a List with a basic POJO called Customer. Customer is a pojo with one property, id. I have a factory that supplies the populated List to the actions List property which i mentioned called gridModel. Heres how i set up my struts.xml file: <constant name="struts.devMode" value="true"/> <constant name="struts.objectFactory" value="guice"/> <package name="org.webhop.ywdc" namespace="/" extends="struts-default,json-default"> <result-types> <result-type name="json" class="com.googlecode.jsonplugin.JSONResult"> </result-type> </result-types> <action name="login" class="org.webhop.ywdc.LoginAction" > <result type="json"></result> <result name="success" type="dispatcher">/pages/uiTags/Success.jsp</result> <result name="error" type="redirect">/pages/uiTags/Login.jsp</result> <interceptor-ref name="cookie"> <param name="cookiesName">JSESSIONID</param> </interceptor-ref> </action> <action name="logout" class="org.webhop.ywdc.LogoutAction" > <result name="success" type="redirect">/pages/uiTags/Login.jsp</result> </action> </package> In the struts.xml file i set the and in my action i listed in the action configuration. Heres my jsp page that the action loads: <%@ taglib prefix="s" uri="/struts-tags" % <%@ taglib prefix="sj" uri="/struts-jquery-tags"% <%@ taglib prefix="sjg" uri="/struts-jquery-grid-tags"% <%@ page language="java" contentType="text/html" import="java.util.*"% Welcome, you have logged in! <s:url id="remoteurl" action="login"/> <sjg:grid id="gridtable" caption="Customer Examples" dataType="json" href="%{remoteurl}" pager="false" gridModel="gridModel" > <sjg:gridColumn name="id" key="true" index="id" title="ID" formatter="integer" sortable="false"/> </sjg:grid> Welcome, you have logged in. <br /> <b>Session Time: </b><%=new Date(session.getLastAccessedTime())%> <h2>Password:<s:property value="password"/></h2> <h2>userId:<s:property value="userId"/></h2> <br /> <a href="<%= request.getContextPath() %>/logout.action">Logout</a><br /><br /> ID: <s:property value="id"/> session id: <s:property value="JSESSIONID"/> </body> Im not really sure how to tell what json the json plugin is creating from the action class. If i did know how i could tell if it wasnt formed properly. As far as I know if I specificy in my action configuration in struts.xml, that the grid, which is set to read json and knows to look for "gridModel" will then automatically load the json to the grid, but its not. Heres my action class: public class LoginAction extends ActionSupport { public String JSESSIONID; public int id; private String userId; private String password; public Members member; public List<Customer> gridModel; public String execute() { Cookie cookie = new Cookie("ywdcsid", password); cookie.setMaxAge(3600); HttpServletResponse response = ServletActionContext.getResponse(); response.addCookie(cookie); HttpServletRequest request = ServletActionContext.getRequest(); Cookie[] ckey = request.getCookies(); for(Cookie c: ckey) { System.out.println(c.getName() + "/cookie_name + " + c.getValue() + "/cookie_value"); } Map requestParameters = ActionContext.getContext().getParameters();//getParameters(); String[] testString = (String[])requestParameters.get("password"); String passwordString = testString[0]; String[] usernameArray = (String[])requestParameters.get("userId"); String usernameString = usernameArray[0]; Injector injector = Guice.createInjector(new GuiceModule()); HibernateConnection connection = injector.getInstance(HibernateConnection.class); AuthenticationServices currentService = injector.getInstance(AuthenticationServices.class); currentService.setConnection(connection); currentService.setInjector(injector); member = currentService.getMemberByUsernamePassword(usernameString, passwordString); userId = member.getUsername(); password = member.getPassword(); CustomerFactory customerFactory = new CustomerFactory(); gridModel = customerFactory.getCustomers(); if(member == null) { return ERROR; } else { id = member.getId(); Map session = ActionContext.getContext().getSession(); session.put(usernameString, member); return SUCCESS; } } public String logout() throws Exception { Map session = ActionContext.getContext().getSession(); session.remove("logged-in"); return SUCCESS; } public List<Customer> getGridModel() { return gridModel; } public void setGridModel(List<Customer> gridModel) { this.gridModel = gridModel; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getJSESSIONID() { return JSESSIONID; } public void setJSESSIONID(String jsessionid) { JSESSIONID = jsessionid; } } Please help me with this problem. You will make my week, as this is a major bottleneck for me :( thanks so much, thebravedave

    Read the article

  • Parsing nested JSON objects with JSON Framework for Objective-C

    - by Sheehan Alam
    I have the following JSON object: { "response": { "status": 200 }, "messages": [ { "message": { "user": "value" "pass": "value", "url": "value" } ] } } I am using JSON-Framework (also tried JSON Touch) to parse through this and create a dictionary. I want to access the "message" block and pull out the "user", "pass" and "url" values. In Obj-C I have the following code: // Create new SBJSON parser object SBJSON *parser = [[SBJSON alloc] init]; // Prepare URL request to download statuses from Twitter NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:myURL]]; // Perform request and get JSON back as a NSData object NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; // Get JSON as a NSString from NSData response NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding]; //Print contents of json-string NSArray *statuses = [parser objectWithString:json_string error:nil]; NSLog(@"Array Contents: %@", [statuses valueForKey:@"messages"]); NSLog(@"Array Count: %d", [statuses count]); NSDictionary *results = [json_string JSONValue]; NSArray *tweets = [[results objectForKey:@"messages"] objectForKey:@"message"]; for (NSDictionary *tweet in tweets) { NSString *url = [tweet objectForKey:@"url"]; NSLog(@"url is: %@",url); } I can pull out "messages" and see all of the "message" blocks, but I am unable to parse deeper and pull out the "user", "pass", and "url".

    Read the article

  • What's wrong with my JSON?

    - by Ronald
    Anybody out there notice anything wrong with this JSON? It validates at JSONLint.com, but neither Chrome nor Firefox's native JSON parse functions will properly parse it. Any ideas? { "result": "{\"players\":[{\"name\":\"User 522\",\"turn\":true,\"score\":0},{\"name\":\"User 925\",\"turn\":false,\"score\":5}],\"enableControls\":false}", "error": "null", "id": "7" }

    Read the article

  • XML ou JSON? (pt-BR)

    - by srecosta
    Depende.Alguns de nós sentem a necessidade de escolher uma nova técnica / tecnologia em detrimento da que estava antes, como uma negação de identidade ou como se tudo que é novo viesse para substituir o que já existe. Chega a parecer, como foi dito num dos episódios de “This Developer’s Life”, que temos de esquecer algo para termos espaço para novos conteúdos. Que temos de abrir mão.Não é bem assim que as coisas funcionam. Eu vejo os colegas abraçando o ASP.NET MVC e condenando o ASP.NET WebForms como o anticristo. E tenho observado a mesma tendência com o uso do JSON para APIs ao invés de XML, como se o XML não servisse mais para nada. Já vi, inclusive, módulos sendo reescritos para trabalhar com JSON, só porque “JSON é melhor” ™.O post continua no meu blog: http://www.srecosta.com/2012/11/22/xml-ou-json/Grande abraço,Eduardo Costa

    Read the article

  • Quick Hint: Formatting JSON for Debugging

    - by Aligned
    Originally posted on: http://geekswithblogs.net/Aligned/archive/2013/06/25/quick-hint-formatting-json-for-debugging.aspxI needed a way to quickly format JSON that I copied from the Network view in Google Chrome Developer Tools. A co-worker pointed me to the Notepad++ (or use Chocolatey to install Notepad++) plugin JSMin. Now all I have to do is copy the JSON into Notepad++ and Alt + Ctrl + M and I can see it easily.

    Read the article

  • How to convert datatable to json string using json.net?

    - by Pandiya Chendur
    How to convert datatable to json using json.net? Any suggestion... I ve downloaded the necessary binaries... Which class should i use to get the conversion of my datatable to json? Thus far used this method to get json string by passing my datatable... public string GetJSONString(DataTable table) { StringBuilder headStrBuilder = new StringBuilder(table.Columns.Count * 5); //pre-allocate some space, default is 16 bytes for (int i = 0; i < table.Columns.Count; i++) { headStrBuilder.AppendFormat("\"{0}\" : \"{0}{1}¾\",", table.Columns[i].Caption, i); } headStrBuilder.Remove(headStrBuilder.Length - 1, 1); // trim away last , StringBuilder sb = new StringBuilder(table.Rows.Count * 5); //pre-allocate some space sb.Append("{\""); sb.Append(table.TableName); sb.Append("\" : ["); for (int i = 0; i < table.Rows.Count; i++) { string tempStr = headStrBuilder.ToString(); sb.Append("{"); for (int j = 0; j < table.Columns.Count; j++) { table.Rows[i][j] = table.Rows[i][j].ToString().Replace("'", ""); tempStr = tempStr.Replace(table.Columns[j] + j.ToString() + "¾", table.Rows[i][j].ToString()); } sb.Append(tempStr + "},"); } sb.Remove(sb.Length - 1, 1); // trim last , sb.Append("]}"); return sb.ToString(); } Now i thought of using json.net but dont know where to get started....

    Read the article

  • Serializing Python bytestrings to JSON, preserving ordinal character values

    - by Doctor J
    I have some binary data produced as base-256 bytestrings in Python (2.x). I need to read these into JavaScript, preserving the ordinal value of each byte (char) in the string. If you'll allow me to mix languages, I want to encode a string s in Python such that ord(s[i]) == s.charCodeAt(i) after I've read it back into JavaScript. The cleanest way to do this seems to be to serialize my Python strings to JSON. However, json.dump doesn't like my bytestrings, despite fiddling with the ensure_ascii and encoding parameters. Is there a way to encode bytestrings to Unicode strings that preserves ordinal character values? Otherwise I think I need to encode the characters above the ASCII range into JSON-style \u1234 escapes; but a codec like this does not seem to be among Python's codecs. Is there an easy way to serialize Python bytestrings to JSON, preserving char values, or do I need to write my own encoder?

    Read the article

  • Parse JSON in C#

    - by Ender
    I'm trying to parse some JSON data from the Google AJAX Search API. I have this URL and I'd like to break it down so that the results are displayed. I've currently written this code, but I'm pretty lost in regards of what to do next, although there are a number of examples out there with simplified JSON strings. Being new to C# and .NET in general I've struggled to get a genuine text output for my ASP.NET page so I've been recommended to give JSON.NET a try. Could anyone point me in the right direction to just simply writing some code that'll take in JSON from the Google AJAX Search API and print it out to the screen? EDIT: I think I've made some progress in regards to getting some code working using DataContractJsonSerializer. Here is the code I have so far. Any advice on whether this is close to working and/or how I would output my results in a clean format? EDIT 2: I've followed the advice from Dreas Grech and the StackOverflowException has gone. However, now I am getting no output. Any ideas on where to go next? EDIT 3: ALL FIXED! All results are working fine. Thank you again Dreas Grech! using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.ServiceModel.Web; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.IO; using System.Text; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { GoogleSearchResults g1 = new GoogleSearchResults(); const string json = @"{""responseData"": {""results"":[{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.cheese.com/"",""url"":""http://www.cheese.com/"",""visibleUrl"":""www.cheese.com"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:bkg1gwNt8u4J:www.cheese.com"",""title"":""\u003cb\u003eCHEESE\u003c/b\u003e.COM - All about \u003cb\u003echeese\u003c/b\u003e!."",""titleNoFormatting"":""CHEESE.COM - All about cheese!."",""content"":""\u003cb\u003eCheese\u003c/b\u003e - everything you want to know about it. Search \u003cb\u003echeese\u003c/b\u003e by name, by types of milk, by textures and by countries.""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://en.wikipedia.org/wiki/Cheese"",""url"":""http://en.wikipedia.org/wiki/Cheese"",""visibleUrl"":""en.wikipedia.org"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:n9icdgMlCXIJ:en.wikipedia.org"",""title"":""\u003cb\u003eCheese\u003c/b\u003e - Wikipedia, the free encyclopedia"",""titleNoFormatting"":""Cheese - Wikipedia, the free encyclopedia"",""content"":""\u003cb\u003eCheese\u003c/b\u003e is a food consisting of proteins and fat from milk, usually the milk of cows, buffalo, goats, or sheep. It is produced by coagulation of the milk \u003cb\u003e...\u003c/b\u003e""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.ilovecheese.com/"",""url"":""http://www.ilovecheese.com/"",""visibleUrl"":""www.ilovecheese.com"",""cacheUrl"":""http://www.google.com/search?q\u003dcache:GBhRR8ytMhQJ:www.ilovecheese.com"",""title"":""I Love \u003cb\u003eCheese\u003c/b\u003e!, Homepage"",""titleNoFormatting"":""I Love Cheese!, Homepage"",""content"":""The American Dairy Association\u0026#39;s official site includes recipes and information on nutrition and storage of \u003cb\u003echeese\u003c/b\u003e.""},{""GsearchResultClass"":""GwebSearch"",""unescapedUrl"":""http://www.gnome.org/projects/cheese/"",""url"":""http://www.g

    Read the article

  • JSON Formatting with Jersey, Jackson, & json.org/java Parser using Curl Command

    - by socal_javaguy
    Using Java 6, Tomcat 7, Jersey 1.15, Jackson 2.0.6 (from FasterXml maven repo), & www.json.org parser, I am trying to pretty print the JSON String so it will look indented by the curl -X GET command line. I created a simple web service which has the following architecture: My POJOs (model classes): Family.java import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Family { private String father; private String mother; private List<Children> children; // Getter & Setters } Children.java import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Children { private String name; private String age; private String gender; // Getters & Setters } Using a Utility Class, I decided to hard code the POJOs as follows: public class FamilyUtil { public static Family getFamily() { Family family = new Family(); family.setFather("Joe"); family.setMother("Jennifer"); Children child = new Children(); child.setName("Jimmy"); child.setAge("12"); child.setGender("male"); List<Children> children = new ArrayList<Children>(); children.add(child); family.setChildren(children); return family; } } My web service: import java.io.IOException; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jettison.json.JSONException; import org.json.JSONObject; import org.json.JSONTokener; import com.myapp.controller.myappController; import com.myapp.resource.output.HostingSegmentOutput; import com.myapp.util.FamilyUtil; @Path("") public class MyWebService { @GET @Produces(MediaType.APPLICATION_JSON) public static String getFamily() throws IOException, JsonGenerationException, JsonMappingException, JSONException, org.json.JSONException { ObjectMapper mapper = new ObjectMapper(); String uglyJsonString = mapper.writeValueAsString(FamilyUtil.getFamily()); System.out.println(uglyJsonString); JSONTokener tokener = new JSONTokener(uglyJsonString); JSONObject finalResult = new JSONObject(tokener); return finalResult.toString(4); } } When I run this using: curl -X GET http://localhost:8080/mywebservice I get this in my Eclipse's console: {"father":"Joe","mother":"Jennifer","children":[{"name":"Jimmy","age":"12","gender":"male"}]} But from the curl command on the command line (this response is more important): "{\n \"mother\": \"Jennifer\",\n \"children\": [{\n \"age\": \"12\",\n \"name\": \"Jimmy\",\n \"gender\": \"male\"\n }],\n \"father\": \"Joe\"\n}" This is adding newline escape sequences and placing double quotes (but not indenting like it should it does have 4 spaces after the new line but its all in one line). Would appreciate it if someone could point me in the right direction.

    Read the article

  • Calling a REST Based JSON Endpoint with HTTP POST and WCF

    - by Wallym
    Note: I always forget this stuff, so I'm putting it my blog to help me remember it.Calling a JSON REST based service with some params isn't that hard.  I have an endpoint that has this interface:        [WebInvoke(UriTemplate = "/Login",             Method="POST",             BodyStyle = WebMessageBodyStyle.Wrapped,            RequestFormat = WebMessageFormat.Json,            ResponseFormat = WebMessageFormat.Json )]        [OperationContract]        bool Login(LoginData ld); The LoginData class is defined like this:    [DataContract]    public class LoginData    {        [DataMember]        public string UserName { get; set; }        [DataMember]        public string PassWord { get; set; }        [DataMember]        public string AppKey { get; set; }    } Now that you see my method to call to login as well as the class that is passed for the login, the body of the login request looks like this:{ "ld" : {  "UserName":"testuser", "PassWord":"ackkkk", "AppKey":"blah" } } The header (in Fiddler), looks like this:User-Agent: FiddlerHost: hostnameContent-Length: 76Content-Type: application/json And finally, my url to POST against is:http://www.something.com/...../someservice.svc/LoginAnd there you have it, calling a WCF JSON Endpoint thru REST (and HTTP POST)

    Read the article

  • Design considerations on JSON schema for scalars with a consistent attachment property

    - by casperOne
    I'm trying to create a JSON schema for the results of doing statistical analysis based on disparate pieces of data. The current schema I have looks something like this: { // Basic key information. video : "http://www.youtube.com/watch?v=7uwfjpfK0jo", start : "00:00:00", end : null, // For results of analysis, to be populated: // *** This is where it gets interesting *** analysis : { game : { value: "Super Street Fighter 4: Arcade Edition Ver. 2012", confidence: 0.9725 } teams : [ { player : { value : "Desk", confidence: 0.95, } characters : [ { value : "Hakan", confidence: 0.80 } ] } ] } } The issue is the tuples that are used to store a value and the confidence related to that value (i.e. { value : "some value", confidence : 0.85 }), populated after the results of the analysis. This leads to a creep of this tuple for every value. Take a fully-fleshed out value from the characters array: { name : { value : "Hakan", confidence: 0.80 } ultra : { value: 1, confidence: 0.90 } } As the structures that represent the values become more and more detailed (and more analysis is done on them to try and determine the confidence behind that analysis), the nesting of the tuples adds great deal of noise to the overall structure, considering that the final result (when verified) will be: { name : "Hakan", ultra : 1 } (And recall that this is just a nested value) In .NET (in which I'll be using to work with this data), I'd have a little helper like this: public class UnknownValue<T> { T Value { get; set; } double? Confidence { get; set; } } Which I'd then use like so: public class Character { public UnknownValue<Character> Name { get; set; } } While the same as the JSON representation in code, it doesn't have the same creep because I don't have to redefine the tuple every time and property accessors hide the appearance of creep. Of course, this is an apples-to-oranges comparison, the above is code while the JSON is data. Is there a more formalized/cleaner/best practice way of containing the creep of these tuples in JSON, or is the approach above an accepted approach for the type of data I'm trying to store (and I'm just perceiving it the wrong way)? Note, this is being represented in JSON because this will ultimately go in a document database (something like RavenDB or elasticsearch). I'm not concerned about being able to serialize into the object above, because I can always use data transfer objects to facilitate getting data into/out of my underlying data store.

    Read the article

  • How to get around the Circular Reference issue with JSON and Entity

    - by DanScan
    I have been experimenting with creating a website that leverages MVC with JSON for my presentation layer and Entity framework for data model/database. My Issue comes into play with serializing my Model objects into JSON. I am using the code first method to create my database. When doing the code first method a one to many relationship (parent/child) requires the child to have a reference back to the parent. (Example code my be a typo but you get the picture) class parent { public List<child> Children{get;set;} public int Id{get;set;} } class child { public int ParentId{get;set;} [ForeignKey("ParentId")] public parent MyParent{get;set;} public string name{get;set;} } When returning a "parent" object via a JsonResult a circular reference error is thrown because "child" has a property of class parent. I have tried the ScriptIgnore attribute but I lose the ability to look at the child objects. I will need to display information in a parent child view at some point. I have tried to make base classes for both parent and child that do not have a circular reference. Unfortunately when I attempt to send the baseParent and baseChild these are read by the JSON Parser as their derived classes (I am pretty sure this concept is escaping me). Base.baseParent basep = (Base.baseParent)parent; return Json(basep, JsonRequestBehavior.AllowGet); The one solution I have come up with is to create "View" Models. I create simple versions of the database models that do not include the reference to the parent class. These view models each have method to return the Database Version and a constructor that takes the database model as a parameter (viewmodel.name = databasemodel.name). This method seems forced although it works. NOTE:I am posting here because I think this is more discussion worthy. I could leverage a different design pattern to over come this issue or it could be as simple as using a different attribute on my model. In my searching I have not seen a good method to overcome this problem. My end goal would be to have a nice MVC application that heavily leverages JSON for communicating with the server and displaying data. While maintaining a consistant model across layers (or as best as I can come up with).

    Read the article

  • json-framework: EXC_BAD_ACCESS on stringWithObject

    - by Vegar
    UPDATE: I found that the reason for the previous error was an error in the documentation. The method should be named proxyForJson, not jsonProxyObject... But I'm still stuck, though. I now get an EXC_BAD_ACCESS error inside stringWithObject some where. Any clues? UPDATE 2: My proxyForJson implementation is a cut-n-paste from then documentation: - (id)proxyForJson { return [NSDictionary dictionaryWithObjectsAndKeys: Navn, @"Navn", Adresse, @"Adresse", Alder, @"Alder", nil]; } Trying to make json serialization work for my custom objective-c class. As I understand the documentation, json-framework can serialize custom objects, if they implement the jsonProxyObject method. So I have this class: @interface MyObject : NSObject { NSString *Name; NSString *Addresse; NSInteger Age; } @property (nonatomic, retain) NSString *Name; @property (nonatomic, retain) NSString *Addresse; @property (nonatomic, assign) NSInteger Age; - (id)jsonProxyObject; @end And I try to serialize an array with some instances in it: [json stringWithObject:list error:&error]; But all I get is he following error: "JSON serialisation not supported for MyObject" I guess the jsonWriter can't find my jsonProxyObject method for some reason, buy why? Regards.

    Read the article

  • Fastest way to parse big json android

    - by jem88
    I've a doubt that doesn't let me sleep! :D I'm currently working with big json files, with many levels. I parse these object using the 'default' android way, so I read the response with a ByteArrayOutputStream, get a string and create a JSONObject from the string. All fine here. Now, I've to parse the content of the json to get the objects of my interest, and I really can't find a better way that parse it manually, like this: String status = jsonObject.getString("status"); Boolean isLogged = jsonObject.getBoolean("is_logged"); ArrayList<Genre> genresList = new ArrayList<Genre>(); // Get jsonObject with genres JSONObject jObjGenres = jsonObject.getJSONObject("genres"); // Instantiate an iterator on jsonObject keys Iterator<?> keys = jObjGenres.keys(); // Iterate on keys while( keys.hasNext() ) { String key = (String) keys.next(); JSONObject jObjGenre = jObjGenres.getJSONObject(key); // Create genre object Genre genre = new Genre( jObjGenre.getInt("id_genre"), jObjGenre.getString("string"), jObjGenre.getString("icon") ); genresList.add(genre); } // Get languages list JSONObject jObjLanguages = jsonObject.getJSONObject("languages"); Iterator jLangKey = jObjLanguages.keys(); List<Language> langList = new ArrayList<Language>(); while (jLangKey.hasNext()) { // Iterate on jlangKey obj String key = (String) jLangKey.next(); JSONObject jCurrentLang = (JSONObject) jObjLanguages.get(key); Language lang = new Language( jCurrentLang.getString("id_lang"), jCurrentLang.getString("name"), jCurrentLang.getString("code"), jCurrentLang.getString("active").equals("1") ); langList.add(lang); } I think this is really ugly, frustrating, timewaster, and fragile. I've seen parser like json-smart and Gson... but seems difficult to parse a json with many levels, and get the objects! But I guess that must be a better way... Any idea? Every suggestion will be really appreciated. Thanks in advance!

    Read the article

  • Python read multiline JSON

    - by Paul W
    I have been trying to use JSON to store settings for a program. I can't seem to get Python 2.6 's JSON Decoder to decode multi-line JSON strings... Here is example input: .settings file: """ {\ 'user':'username',\ 'password':'passwd',\ }\ """ I have tried a couple other syntaxes for this file, which I will specify below (with the traceback they cause). My python code for reading the file in is import json settings_text = open(".settings", "r").read() settings = json.loads(settings_text) The Traceback for this is: Traceback (most recent call last): File "json_test.py", line 4, in <module> print json.loads(text) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/__init__.py", line 307, in loads return _default_decoder.decode(s) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 322, in decode raise ValueError(errmsg("Extra data", s, end, len(s))) ValueError: Extra data: line 1 column 2 - line 7 column 1 (char 2 - 41) I assume the "Extra data" is the triple-quote. Here are the other syntaxes I have tried for the .settings file, with their respective Tracebacks: "{\ 'user':'username',\ 'pass':'passwd'\ }" Traceback (most recent call last): File "json_test.py", line 4, in <module> print json.loads(text) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/__init__.py", line 307, in loads return _default_decoder.decode(s) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 319, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 336, in raw_decode obj, end = self._scanner.iterscan(s, **kw).next() File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/scanner.py", line 55, in iterscan rval, next_pos = action(m, context) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 155, in JSONString return scanstring(match.string, match.end(), encoding, strict) ValueError: Invalid \escape: line 1 column 2 (char 2) '{\ "user":"username",\ "pass":"passwd",\ }' Traceback (most recent call last): File "json_test.py", line 4, in <module> print json.loads(text) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/__init__.py", line 307, in loads return _default_decoder.decode(s) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 319, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/json/decoder.py", line 338, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded If I put the settings all on one line, it decodes fine.

    Read the article

  • Json.Net CustomSerialization

    - by BonyT
    I am serializing a collection of objects that contains a dictionary called dynamic properties. The default Json emitted looks like this: [{"dynamicProperties":{"WatchId":7771,"Issues":0,"WatchType":"x","Location":"Equinix Source","Name":"PI_5570_5580"}}, {"dynamicProperties":{"WatchId":7769,"Issues":0,"WatchType":"x","Location":"Equinix Source","Name":"PI_5570_5574"}}, {"dynamicProperties":{"WatchId":7767,"Issues":0,"WatchType":"x","Location":"Equinix Source","Name":"PI_5570_5572"}}, {"dynamicProperties":{"WatchId":7765,"Issues":0,"WatchType":"y","Location":"Equinix Source","Name":"highlight_SM"}}, {"dynamicProperties":{"WatchId":8432,"Issues":0,"WatchType":"y","Location":"Test Devices","Name":"Cisco1700PI"}}] I'd like to produce Json that looks like this: [{"WatchId":7771,"Issues":0,"WatchType":"x","Location":"Equinix Source","Name":"PI_5570_5580"}, {"WatchId":7769,"Issues":0,"WatchType":"x","Location":"Equinix Source","Name":"PI_5570_5574"}, {"WatchId":7767,"Issues":0,"WatchType":"x","Location":"Equinix Source","Name":"PI_5570_5572"}, {"WatchId":7765,"Issues":0,"WatchType":"y","Location":"Equinix Source","Name":"highlight_SM"}, {"WatchId":8432,"Issues":0,"WatchType":"y","Location":"Test Devices","Name":"Cisco1700PI"}] From reading the Json.Net documentation it looks like I could build a CustomContractResolver for my class, but I cannot find any details on how to go about this... Can anyone shed any light on the direction I should be looking in?

    Read the article

  • Logging in JSON Effect on Performance

    - by Pius
    I see more and more articles about logging in JSON. You can also find one on NodeJS blog. Why does everyone like it so much? I can only see more operations getting involved: A couple new objects being created. Stringifying objects, which either involves calculating string length or multiple string allocations. GCing all the crap that was created. Is there any test on performance when using JSON logging and regular string logging? Do people use JSON (for logging) in enterprise projects?

    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

  • JSON encoding on RTL languages

    - by Lev
    Hi, I'm using JSON to integrate open flash chart to my web page. When I have a Right to Left language string which contains more the one word the JSON encodes it backwards (For example: "Hello world" is encoded as "world hello"). The string is extracted from a database, there for can be of any language. How do I force the correct encoding of Right to Left language without ruining other languages? Thanks

    Read the article

  • Is JSON.stringify() reliable for serializing JSON objects?

    - by Colin
    I need to send full objects from Javascript to PHP. It seemed pretty obvious to do JSON.stringify() and then json_decode() on the PHP end, but will this allow for strings with ":" and ","? Do I need to run an escape() function on big user input strings that may cause an issue? What would that escape function be? I don't think escape works for my purposes. Are there any downsides to JSON.stringify() I need to know about? Thanks

    Read the article

  • JSON Rpc libraries for use with .NET

    - by Deeptechtons
    I am looking into JSON RPC libraries for .net that are free to use in commercial applications. Up until now i just seem to have found JROCK. What other libraries, architecture have i got similar to JRock for .NET 2.0 What is the difference between a [WebMethod] in asmx web-service returning a instance of a class and a JSON Rpc method as in the JRock website page. Do i have any usability benefits, performance benefits or any benefits of using one over the other

    Read the article

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