JSON parsing using Gson for Java

前端 未结 11 2280
青春惊慌失措
青春惊慌失措 2020-11-22 04:57

I would like to parse data from JSON which is of type String. I am using Google Gson.

I have:

jsonLine = \"
{
 \"data\": {
  \"translati         


        
11条回答
  •  时光说笑
    2020-11-22 05:26

    In my first gson application I avoided using additional classes to catch values mainly because I use json for config matters

    despite the lack of information (even gson page), that's what I found and used:

    starting from

    Map jsonJavaRootObject = new Gson().fromJson("{/*whatever your mega complex object*/}", Map.class)
    

    Each time gson sees a {}, it creates a Map (actually a gson StringMap )

    Each time gson sees a '', it creates a String

    Each time gson sees a number, it creates a Double

    Each time gson sees a [], it creates an ArrayList

    You can use this facts (combined) to your advantage

    Finally this is the code that makes the thing

            Map javaRootMapObject = new Gson().fromJson(jsonLine, Map.class);
    
        System.out.println(
            (
                (Map)
                (
                    (List)
                    (
                        (Map)
                        (
                            javaRootMapObject.get("data")
                        )
                     ).get("translations")
                ).get(0)
            ).get("translatedText")
        );
    

提交回复
热议问题