java - Cannot cast from JsonElement to String while parsing from the JSON file -
this first code reading json file keep getting error message: can not cast jasonelement string
import java.io.filereader; import com.google.gson.jsonobject; import com.google.gson.jsonparser; public class json { public static void main(string args[]) { jsonparser parser = new jsonparser(); try { object obj = parser.parse(new filereader("c:\\users\\dell\\eclipse- workspace\\assignment\\data.json")); jsonobject jsonobject = (jsonobject) obj; string name = (string) jsonobject.get("name"); string author = (string) jsonobject.get("author"); system.out.println("name: " + name); system.out.println("author: " + author); } catch (exception e) { e.printstacktrace(); } } }
excuse me silly mistakes. still beginner
it depends on want.
if name
needs actual json string value (as in, must { "name": "str" }
, not { "name": [] }
), should jsonobject.get("name").getasstring()
. causes error if isn't string, desirable.
otherwise, use jsonobject.get("name").tostring()
, returns valid json value, string
. e.g.
{ "name": "a" } -> "a" (that's string, 3 characters, 2 quote marks , 'a') { "name": false } -> false (that's string, 5 chars, no quotes)
Comments
Post a Comment