json - 从 NSMutableArray 快速创建 jsonArray

标签 json swift nsmutablearray

我试过了。但我没有得到 jsonArray,我不知道我该怎么做。我想将 jsonArray 作为字符串。你能帮帮我吗?

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

} 

最佳答案

最好是

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

struct Item:Decodable {

 // add properties 

}

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

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

关于json - 从 NSMutableArray 快速创建 jsonArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53724603/

相关文章:

json - 将 CSV/XLS 转换为 JSON?

html - 在 HTML 中漂亮地打印 JSON 字符串

ios - 保存 uicollectionview 单元格更新中的数据

ios - NSPredicate - 多个条件的不区分大小写的过滤

iPhone/iOS 如何在多个文件夹中加载大量图像并在表格 View 中显示?

objective-c - 将 NSmutableArray 保存到文件并加载

java - gson 自定义将 json 键转为字符串

json - 如何使用 AlamofireObjectMapper 将 JSON 字典添加到 Realm

ios - WKWebView 不加载某些 URL

ios - 使用 AppDelegate 为核心数据定义上下文作为单例