Coder Social home page Coder Social logo

Array<Object> 这样得出来的json 是使用不了的 都变成了[Any?,...] 了...类型丢了.但是打印出来的json是正常的 about handyjson HOT 4 CLOSED

alibaba avatar alibaba commented on May 5, 2024
Array 这样得出来的json 是使用不了的 都变成了[Any?,...] 了...类型丢了.但是打印出来的json是正常的

from handyjson.

Comments (4)

codetalks-new avatar codetalks-new commented on May 5, 2024

@longlylong 给个例子看看. 不太理解你说的.

from handyjson.

longlylong avatar longlylong commented on May 5, 2024

class A :HandJson{
var p = Array<P>()
}
class P:HandJson{
var name = "dddd"
}
A().toJSON()
这个的结果就是{"A":{p:[Any?],[Any?],...}}
正确应该是{"A":{p:["name":"dddd"],["name":"dddd"],...}}

from handyjson.

codetalks-new avatar codetalks-new commented on May 5, 2024

@longlylong 我在我的一个 PR 中修复了些问题.
#77
你可以试试我的这个分支.

from handyjson.

xuyecan avatar xuyecan commented on May 5, 2024

我认真考虑了这个问题,觉得这是理论上的限制,没有办法做出改进的。

toJSON() 接口返回的是一个字典,字典中各个值,是运行时通过反射的方式解析 A 类得到的,也就是,需要到运行时,才可能检测到各个值的类型。而你这里说的类型是编译期的概念。打个比方,如果你能知道 let a = A().toJSON() 得到的 a[String: [[String: String]] 类型,意味着你可以写代码的时候,IDE就可以给你补全 a["p"].count 后边的 .count(有类型信息)。但这个 a 是运行时才知道的,不可能编译期就获得它的类型。

也就是说,toJSON() 返回的字典,每个值的类型都是和 A 类对应的,但你只能通过强转的形式,让它成为对应的类型(因为你可以根据对应关系明白每个转换出来的值会是什么类型)。如:

if let p = A().toJSON()?["p"] as? [Any?] {
    if let first = p.first as? String {
        print(first)
    }
}

from handyjson.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.