Having a jString : JString value holding an "abc" string inside I get "JString(abc)" : String if I call jString.toString. How do I get "abc" : String instead?
            Asked
            
        
        
            Active
            
        
            Viewed 1.7k times
        
    21
            
            
         
    
    
        Ivan
        
- 63,011
- 101
- 250
- 382
- 
                    1I've found the solution to use `jString.values : String` but I feel uncertain if it's correct - why is it called `values` (not a `value`) if there's just a `String`? – Ivan Oct 16 '11 at 03:19
4 Answers
19
            
            
        To extract a value from JValue you can use any method described here: What is the most straightforward way to parse JSON in Scala?
For instance:
json.extract[String]
You can use 'render' function to convert any JValue to printable format. Then either 'pretty' or 'compact' will convert that to a String.
compact(render(json))
or
pretty(render(json))
- 
                    I don't want to render JSON. I want the opposite - to extract a string value of a property of an object serialized in JSON and I've already isolated that only field into a separate JString, containing nothing but the value I need. – Ivan Oct 16 '11 at 09:18
7
            
            
        I believe the best way is to use match:
val x = ... (whatever, maybe it's a JString)
x match {
  case JString(s) => do something with s
  case _          => oops, something went wrong
}
 
    
    
        Vlad Patryshev
        
- 1,379
- 1
- 10
- 16
7
            
            
        val jstring=JString("abc")
implicit val formats = net.liftweb.json.DefaultFormats 
System.out.println(jstring.extract[String])
 
    
    
        Win Myo Htet
        
- 5,377
- 3
- 38
- 56
1
            
            
        This was asked a while ago, but I wanted a simple one-line helper that would get my string for me in the context of an expression, so I wrote this little thing inside of an object called Get:
  object Get {
    def string(value: JValue): String = {                                                                                                               
      val JString(result) = value                                                                                            
      result                                                                                                                              
    }
  ...
  }
This way I can just do, e.g., val myString = Get.string(jsonStringValue)
 
    
    
        Necro
        
- 521
- 5
- 10
 
    