0

I need to create a JsonString from a NSString, without any key in ObjC. All tutorials talks about serialization from NSDictionary or NSData.

My string is like @"fr-FR". The result i'm looking for is like @"{"fr-FR"}", but dynamically. Can't do it myself because i will need to do the same stuff for different kind of arguments.

Thanks in advance :)

4
  • 2
    {fr-FR} isn't valid JSON, so I'm a bit unsure what you want to do here Commented May 4, 2012 at 9:14
  • I know. The result I need is the same that the c# JSonConvert.SerializeObject("fr-FR"); The result of this function is {"fr-FR"} Commented May 4, 2012 at 9:16
  • @user1147981 It seems that you only want your string wrapped in curly braces right? If that is the case check my answer below. Commented May 4, 2012 at 9:18
  • The problem is that what you are asking for is not valid JSON so no JSON serialisation framework is going to be of any help. Alladinian's answer looks the best to get what you want. Commented May 4, 2012 at 9:30

4 Answers 4

2

To achieve the result you are asking for (even if it's not a proper JSON) you could try something like this:

NSString *myString = @"fr-FR"; // Or whatever
NSString *result = [NSString stringWithFormat:@"{\"%@\"}", myString];
Sign up to request clarification or add additional context in comments.

Comments

1

You need to use a JSON framework/library, for example TouchJSON, and then you can do the following to encode your NSString:

theData = [[CJSONSerializer serializer] serializeObject:theString
                                                  error:&theError];

(from the demo code here).

Comments

1

You could use NSJSONSerialization class if you develop on IOS 5 +

create data with your string

NSString *myString = @"fr-FR"; // Or whatever
NSString *result = [NSString stringWithFormat:@"{%@}", myString];
NSData* data=[result dataUsingEncoding:NSUTF8StringEncoding];

and then use

+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error

to create your JSON object

(just typed, not tested)

Comments

0

IMHO after reading the json spec again ( http://www.json.org ) {"string"} isn't valid json and the code you are using in c# produces invalid results. However, if you need to communicate with c# code that acts this way you should just encode the string itself using a JSON library and then afterwards pack it in curly braces. That way you get all the escaping needed for JSON for special cases (e.g. quotes and whatnot) which you don't if you just add quotes and braces manually.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.