How to convert JSON to a type in Scala

后端 未结 5 1809
野性不改
野性不改 2021-02-19 04:06

My problem is I receive an JSON text from say, twitter. Then I want to convert this text to an native object in scala. Is there a standard method to do this? I\'m also using Pla

5条回答
  •  隐瞒了意图╮
    2021-02-19 04:38

    I suggest to use Jackson JSON processor. It works both for Java and Scala. You just add annotations to your classes which describe how you want to map JSON data to your native objects.

    An example:

    import scala.reflect.BeanProperty
    import org.codehaus.jackson.map.ObjectMapper;
    import org.codehaus.jackson.annotate._
    
    class User {
      @BeanProperty var gender: String = null
      @BeanProperty var verified: Boolean = false
      @BeanProperty var userImage: Array[Byte] = null
      @BeanProperty var name: Name = null
    }
    
    case class Name {
      @BeanProperty var first: String = null;
      @BeanProperty var last: String = null;
    }
    
    object Json {
      def main(argv: Array[String]) {
        val input = """{
      "name" : { "first" : "Joe", "last" : "Sixpack" },
      "verified" : false,
      "userImage" : "Rm9vYmFyIQ=="
    }""";
    
        val mapper = new ObjectMapper(); // can reuse, share globally
        val user: User = mapper.readValue(input, classOf[User]);
    
        print(user.name.first);
      }
    }
    

    This solution has a slight hassle that you have to annotate every field with @BeanProperty, but I don't know a simpler way.


    Remark: As far as I know, Jackson doesn't use javax.bean.Introspector, it tries to find getters/setters by examining the methods by itself. If it did, things would have been easier, it would be possible to write just

    @scala.reflect.BeanInfo
    case class Name {
        var first: String;
        var last: String;
    }
    

提交回复
热议问题