Konstantin Loginov
Konstantin Loginov

Reputation: 16010

Convert plain string to JSON and back in Swift

Let's say there's a JSON-string I got from server: "\"3\"" (with quotes, i.e. length == 3 here)

In Android-world, I can do:

gson.fromJson(json, new TypeToken<String>() {}.getType()); - it returns "3" (i.e. length == 1)

In C#-world, can use NewtonSoft.Json:

JsonConvert.DeserializeObject<string>(json, settings) - it returns "3" (i.e. length == 1)

And other way around, I do have string I want to serialize as a JSON. In Android I'd do gson.toJson("\"3\"") and in C# - JsonConvert.SerializeObject("\"3\"")

The problem with JSONSerialization is that it doesn't treat plain string as a valid JSON: JSONSerialization.isValidJSONObject("\"3\"") == *false*

What would be equivalent in Swift / Obj-C world?

The ugly workaround I've found (except of just adding/removing quotes) so far is to wrap string into 1-item-array to make JSONSerialization happy and then remove "[","]" from resulted JSON-string (and other way around - add "[", "]" before deserialization), but it's a way too disgusting to be the real solution for this problem.

Upvotes: 1

Views: 9333

Answers (1)

Martin R
Martin R

Reputation: 540075

When de-serializing JSON which does not have an array or dictionary as top-level object you can pass the .allowFragments option:

let jsonString =  "\"3\""
let jsonData = jsonString.data(using: .utf8)!

let json = try! JSONSerialization.jsonObject(with: jsonData, options: .allowFragments)

if let str = json as? String {
    print(str) // 3
}

However, there seems to be no way to serialize a plain string to JSON with the JSONSerialization class from the Foundation library.

Note that according to the JSON specification, a JSON object is a collection of name/value pairs (dictionary) or an ordered list of values (array). A single string is not a valid JSON object.

Upvotes: 5

Related Questions