最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

swift - Creating a list from a json file - Stack Overflow

programmeradmin2浏览0评论

I am trying to display a list of company names from a 2 dimensional json array. I think this code is trying to find a single value? Please can you tell me how to try to return an array (i.e. all the "names" in the json file?)

 if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? Array<String>{
    print("test_getPrice120")
    if let name = json[0]["name"] as? String{
    print("test_getPrice122")
    print(name)
    }
}

The if let name = json[0]["name"] as? String{ line fails with error message "no exact matches in call to subscript"

The json file has the structure:

 [{"id":"sdfgfm8fec","name":"Marta Inc"},     
  {"id":"sdfge8xvny","name":"Laud"},
  {"id":"r3z5y4sqb","name":"Lynx}]

Is the 1st dimension of the json file implied to be [0], [1], [2] even though it is not explicitly shown in the json file?

I am trying to display a list of company names from a 2 dimensional json array. I think this code is trying to find a single value? Please can you tell me how to try to return an array (i.e. all the "names" in the json file?)

 if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? Array<String>{
    print("test_getPrice120")
    if let name = json[0]["name"] as? String{
    print("test_getPrice122")
    print(name)
    }
}

The if let name = json[0]["name"] as? String{ line fails with error message "no exact matches in call to subscript"

The json file has the structure:

 [{"id":"sdfgfm8fec","name":"Marta Inc"},     
  {"id":"sdfge8xvny","name":"Laud"},
  {"id":"r3z5y4sqb","name":"Lynx}]

Is the 1st dimension of the json file implied to be [0], [1], [2] even though it is not explicitly shown in the json file?

Share Improve this question edited 1 hour ago Naveed Ahmed 4672 silver badges10 bronze badges asked 3 hours ago NibblesNibbles 758 bronze badges 1
  • Why do you insist on calling it a two-dimensional array when it isn't? It will only lead to confusion and irritation if you label things incorrectly. – Joakim Danielson Commented 1 hour ago
Add a comment  | 

2 Answers 2

Reset to default 0

You could try a different approach to decoding your json data, using a Codable struct, such as:

 struct Entry: Identifiable, Codable {
    let id, name: String
 }
  
        
    
    do {
         let json = """
    [{"id":"sdfgfm8fec","name":"Marta Inc"},
     {"id":"sdfge8xvny","name":"Laud"},{"id":"r3z5y4sqb","name":"Lynx"}]
    """
         let data = json.data(using: .utf8)!
         let theList = try JSONDecoder().decode([Entry].self, from: data)
         print("\n----> theList: \(theList)\n")
         print("----> theList[0]: \(theList[0])\n")
         if let entry = theList.filter{$0.id == "sdfge8xvny"}.first {
            print("----> entry id: sdfge8xvny is \(entry.name)\n")
         }
      } catch {
         print("----> error: \(error)")
      }

Using SwiftUI example:

struct ContentView: View {
    @State private var entries: [Entry] = []
    
    var body: some View {
        List(entries) { entry in
            Text(entry.name)
        }
        .onAppear {
            do {
                let json = """
    [{"id":"sdfgfm8fec","name":"Marta Inc"},
     {"id":"sdfge8xvny","name":"Laud"},{"id":"r3z5y4sqb","name":"Lynx"}]
    """
                let data = json.data(using: .utf8)!
                entries = try JSONDecoder().decode([Entry].self, from: data)
            } catch {
                print(error)
            }
            
        }
    }
    
}

You could try JSONDecoder instead. If you insist to use JSONSerialization, then you should convert the type to Array<[String: String]> not Array<String>:

if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? Array<[String: String]>{
    print("test_getPrice120")
    if let name = json[0]["name"] {
        print("test_getPrice122")
        print(name)
    }
}
发布评论

评论列表(0)

  1. 暂无评论