Parse JSON array - iphone

I fetch a JSON array from a web service with touchJSON.
Which looks like this:
[{"icecream": {"title": "Banana"}}, {"icecream": {"title": "Strawberry"}}]
I'm not able to parse this into a NSDictionary, because
touchJSON doesn't support JSON arrays.
How do I get my JSON array into a NSDicitionary?
Regards

Have you consider trying another framework? This one seems to support JSON arrays.

Maybe you could use another of the many JSON implementations listed on the JSON homepage.

You can chekc out the JSON webpage, where they provide links to parsing code in dozens of languages. However, at first glance it looks like you're trying to munge from one type of object (the JSON Array) into another that might not be able to capture all the relationships (the NSDictionary). Full disclaimer: I've never used an NSDictionary before.

Related

Converting a String to a Splittable in GWT

I'm maintaining a site written in GWT (2.5.0) that is used internally by our development team, and I've been experimenting with using AutoBeans for client side json parsing. I have a few objects with json that is not well defined — a developer can dump whatever json string he wants in there — so I'm using a Splittable property. In order to support editing this arbitrary json I'd like to convert a String into a Splittable, but I haven't found a straight-forward way of accomplishing this. Do I need to implement this interface myself or resort to something hacky like wrapping the json in another json object I can then decode into a throw-away AutoBean just to get a Splittable of the original json?
StringQuoter is the utility class which we do much of our manual Splittable work with.
Just user StringQuoter.create("some string"); to produce a Splittable whose payload is
"some string"
Once you have that splittable, you can assign it to a key in another splittable with the following method:
Splittable.assign(Splittable parent, String propertyName);
However, if you are trying to convert some arbitrary string which contains a JSON structure into a splittable, use StringQuoter.split(..) to create it. The resulting splittable can be queried as normal (i.e. what keys exist/don't exist, etc).

Converting Objects to plist file then to data

I have an array of objects that consist of several strings, I need to push these up to a web service as XML data. What are the steps involved here? As far as I know I need to convert the objects to a plist file, then convert this file to NSData (?) I can't find anything online that really lays it out..
Any help would be greatly appreciated.
Another approach is JSON. SBJSON is very common and simple to use.
It's a two-liner to get a json string from your array. Then you'll create an NSURLRequest that represents the post and an NSURLConnection that performs the request. Lot's of resources for that on SO and elsewhere.
You can try this or this. I doubt plist files are what you want. All you need is to serialize your object into the xml format your web service requires.

POST a list of items using REST

I'm looking for a convention on how to serialize my data when I have a (long) list of items that I want to POST to the server.
For example, if I have a resource /users and I wanted to POST a new one to it, I'd http-encode the fields for the new user and put it in the request body like this: name=foo&age=20
But if I have a list of users, like this [{ name: 'foo', age: 20 }, { name: 'bar', age: 10 }], is there a conventional way of POSTing this?
I'm thinking name[0]=foo&age[0]=20&name[1]=bar&age[1]=10 but I can't find anything to back it up. What do web servers usually accept/expect?
Quick question which may change my answer: Are you POSTing directly from an HTML form or are you expecting something more sophisticated (e.g. javascript processsing, or not even a web-based client)
If you have a sophisticated enough client, you could just construct a JSON string and POST with a content type of application/json. Then whatever resource is processing the POST could use any number of json libraries to read the posted string and process as is.
Further Rambling:
What framework/languages are you using to construct your REST service? Do they have built-in functionality/conventions to help you?
For example if you're using JAX-RS to build your service, there is a built in annotation #FormParam which can be used to process posted forms... for example: if you posted the following with a content type of application/x-www-form-urlencoded: name=foo&age=20&name=bar&age=10
You could retrieve parallel lists on the service side via:
#POST
#Consumes("application/x-www-form-urlencoded")
public void createUsers(#FormParam("name") List<String> name, #FormParam("age") List<String> age) {
// Store your users
}
But you would then have to deal with the question of what if one list is shorter/longer than the other, how do you resolve that? What happens if a new field is required or optional to create a list of users? (But as I mentioned initially, a JSON array of JSON objects would solve that issue... there are a number of libraries out there that support automagic JSON deserialization in JAX-RS or there is also the option of creating your own MessageBodyReader.
(Disclaimer on the next section: I don't know rails, my experience is more in the Java services world... I'm basing this on this guide). It looks like Rails has a convention of name[]=foo&name[]=bar to process posted data into arrays automagically, and a similar convention to populate structure like user[name]=foo&user[age]=20... Perhaps if you are on rails there is some way to use/abuse both of these features to get the desired result?
Other REST frameworks and languages may have their own conventions and functionality :)
Rails serializes forms on a format not unlike what you suggest. If you have a nested model it encodes it like this:
name=theo&company[name]=acme
(the equivalent JSON would be {"name": "theo", "company": {"name": "acme"}})
I can't say that I've seen a Rails application sending arrays, but there's no reason why it wouldn't work (worst case you would end up with a hash with string keys).
PHP has another convention, if you want to send an array you do
names[]=alice&names[]=bob&names[]=steve
But I don't know how you do nested objects that way.
The HTTP spec, or if it's the URI spec, not sure which atm, actually specifies that if you pass the same argument multiple times you get array of values (instead of the last-wins behaviour of most application frameworks). You can see this in the API docs for Jetty, for example: http://api.dpml.net/org/mortbay/jetty/6.1.5/org/mortbay/jetty/Request.html#getParameterValues(java.lang.String)
However, most of this applies to GET requests, not necessarily POST (but perhaps application/x-url-encoded should adhere to the same standards as GET).
In short, I don't think there is a standard for doing this, POST bodies are a bit of a wild west territory. I think, however, that either you should go with JSON, because it's made to describe structures, and application/x-url-encoded is not, or you should try to represent the structure of your data better, something like:
users[0][name]=foo&users[0][age]=20&users[1][name]=bar&users[1][age]=10
That has some kind of chance of actually being interpretable by a Rails app out of the box, for example.

how can i replace json string?

i want to replace particular data's in json string
Parse it, make the changes you need, then serialize it back out. You didn't say what JSON library you're using, but it should be fairly easy.
Without knowing the specifics of your problem:
[jsonString stringByReplacingOccurrencesOfString:#"replaceme" withString:#"replacement"];
But you're probably far better of using a JSON library.

Parse Query String into a Structured NSDictionary

I have a query string: a=1&b=2&c[1]=3&c[2]=4 etc…
I want a NSDictionary where a => 1, b => 2, c => [3,4]. Notice that that the value for c is an array. It should also be able to handle something like c[1][2]=5 to make an array of arrays c => [[5]].
Of course I can do it myself by splitting on the & and =, but what about other cases such as arrays and arrays of arrays. I want a structured NSDictionary from a POST request queryString and do not want to rewrite the wheel if this already exists.
Are there any class/method, through Apple or 3rd party, that will parse a query string into a structured NSDictionary?
The Google Toolbox for Mac contains a GTMNSDictionaryURLArgumentsAdditions category on NSDictionary which may do what you want.
If you have control over the query string (on the client side), you could send an encoded plist which can be decoded directly into an NSDictionary.
It might be overkill in this case, but ParseKit is an open source tokenizing/parsing toolkit written in Cocoa for Cocoa applications:
http://parsekit.com
it may be of interest to you.
ParseKit is cleanly separated into two components: a Tokenizer and then a high-level parsing toolkit built on top of that. You could use either or both of these components to help with this kind of task. But again, ParseKit may be overkill for this relatively simple parsing task.