Json字符串解码为不同的字符串值

时间:2018-08-06 09:17:13

标签: json

我有这样的JsonArray

[
    {
        "id": "60",
        "variant_id": "0",
        "name": "Grape Tomato- 150gm",
        "category": "10",
        "content": "{\"calories\":\"50\",\"carbohydrate\":\"\",\"fat\":\"\",\"protein\":\"\"}",
        "variant_size": "",
        "types": "{\"ptype\":\"VG\"}",
        "price": "45 ",
        "discription": "<p>Grape tomatoes are hybrid tomatoes in smaller in size and sweet in taste. These are ideal to have especially in salads.</p>\n",
        "item_image": "userfile60.jpg",
        "graph_image": "graphfile60.png",
        "isVariant": "NO"
     },

我正在得到答复。 现在,上述JsonArray的“内容”键就是这样输入字符串formate

{"calories":"50","carbohydrate":"","fat":"","protein":""}

我该如何将这些值放入不同的字符串中,以便随后可以用来显示或使用饼图的值 例如:

String calories = "value" 
String carbohydrate= "value"
Sting fat ="value"
String Protein="value"

从上述回复中..我想以这种模式获取数据,请帮忙。

1 个答案:

答案 0 :(得分:0)

只是为了好玩,请使用Codable协议在Swift中回答。也许有人高兴。

struct YourModel: Codable {
    let id: String
    let variant_id: String
    let name: String
    let category: String
    let content: Content
    let variant_size: String
    let types: Types
    let price: String
    let discription: String
    let item_image: String
    let graph_image: String
    let isVariant: String

    struct Types: Codable {
        let ptype: String
    }

    struct Content: Codable {
        let calories: String
        let carbohydrate: String
        let fat: String
        let protein: String
    }
}

let jsonData = "Your JSON".data(using: .utf8)!
let yourModelArray = try! JSONDecoder().decode([YourModel].self, from: jsonData)