从NSMutableArray快速创建jsonArray

时间:2018-12-11 12:50:59

标签: json swift nsmutablearray

我尝试过那样。但是我没有得到jsonArray并且我不知道该怎么办。我想将jsonArray作为String。你能帮我吗?

public static func createInkitchenJson(additionId : Int64, orderId : Int64)
{
    let dicArray : NSMutableDictionary = NSMutableDictionary();
    let nsArray : NSMutableArray = NSMutableArray();

    for basket in BasketStatic.baskets
    {
        let dicObject : NSMutableDictionary = NSMutableDictionary();
        let model = basket.Product;
        dicObject.setValue(String(additionId), forKey: JsonHeader.ADDITION_ID);
        dicObject.setValue(String(orderId), forKey: JsonHeader.ORDER_ID);
        dicObject.setValue(BasketStatic.table?.getTableName(), forKey: JsonHeader.TABLE_NAME);
        dicObject.setValue(model.Id, forKey: JsonHeader.REQUEST_ID);
        dicObject.setValue(String(basket.RowCount), forKey: JsonHeader.ITEM_COUNT);
        dicObject.setValue(model.Name, forKey: JsonHeader.REQUEST_NAME);
        dicObject.setValue(model.getExtraToString(), forKey: JsonHeader.EXTRAS);
        dicObject.setValue(basket.getType(), forKey: JsonHeader.REQUEST_TYPE);
        dicObject.setValue(EMPTY_FIELD, forKey: JsonHeader.MENU_UNIQUE);
        dicObject.setValue(EMPTY_FIELD, forKey: JsonHeader.MENU_NAME);
        dicObject.setValue(EMPTY_FIELD, forKey: JsonHeader.MENU_ID);
        dicObject.setValue(String(basket.RowPrice), forKey: JsonHeader.PRICE);
        dicObject.setValue(WaiterModel.WAITER_ID, forKey: JsonHeader.CREATED_BY);
        nsArray.add(dicObject);
    }

    // here i want to convert NsMutableArray to jsonArray
    // jsonArray convert to string

} 

1 个答案:

答案 0 :(得分:2)

最好

let arr = [Item(/////),,,,,]
let data  = try? JSONEncoder().encode(arr) 
let str = String(data: data, encoding: .utf8)

struct Item:Decodable {

 // add properties 

}

OR

let data = try? JSONSerialization.data(withJSONObject: dic, options: [])

let str = String(data: data, encoding: .utf8)