【问题标题】:Deserialize JSON object that has no name反序列化没有名称的 JSON 对象
【发布时间】:2016-09-06 17:05:58
【问题描述】:

我们有一个相当奇怪的 JSON 有效负载需要反序列化,但我不确定如何使用 Java 和 Gson 进行。

{ 
  "Red": {
           "Level 1": "Specify Action",
           "Level 2": "Action Taken",
           "Level 3": "No Action Taken"
  },
  "Orange": {
           "Level 4": "Defeat Gannon",
           "Level 5": "Save Princess",
           "Level 6": "Find Triforce"
  }
}

我们可以使用 HashMap 来反序列化各个对象(即“红色”和“橙色”),但我们遇到的问题是试图解释父对象,正如代码所示,它没有名称很容易被钩住。

【问题讨论】:

  • 如果没有变量名,你如何在 HashMap 函数中传递这个有效载荷?
  • 对不起,我不清楚。我只发现我可以使用 HashMap 来表示“红色”和“橙色”对象,但正如您所指出的,我无法传递整个有效负载,因为我不确定如何引用父对象。
  • 父对象是什么意思?
  • payload 的第一行不包含变量名。它只是一个左括号“{”。理想情况下,我希望有效载荷看起来像这样...... { "Colors": "Red": { "Level 1": "Specify Action", "Level 2": "Action Taken", "Level 3": "No Action Taken }, "Orange": { "Level 4": "击败 Gannon", "Level 5": "拯救公主", "Level 6": "找到 Triforce" } }
  • 是什么产生了这个 JSON?人工测试您的程序等?

标签: java json serialization gson deserialization


【解决方案1】:

考虑到您的 JSON 如下所示:

{
    "Red": {
       "Level 1": "Specify Action",
       "Level 2": "Action Taken",
       "Level 3": "No Action Taken"
    },
   "Orange": {
       "Level 4": "Defeat Gannon",
       "Level 5": "Save Princess",
       "Level 6": "Find Triforce"
     }
}

我将使用 HashMap,类似于下面的 Jackson API。我认为使用 GSON 也可以完成类似的操作

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

        import java.io.IOException;
        import java.util.HashMap;
        import java.util.Map;

        public class Test {

            public static void main(String[] args) throws IOException {

                ObjectMapper mapper = new ObjectMapper();
                String jsonInString = "{\n" +
                        "    \"Red\": {\n" +
                        "        \"Level 1\": \"Specify Action\",\n" +
                        "        \"Level 2\": \"Action Taken\",\n" +
                        "        \"Level 3\": \"No Action Taken\"\n" +
                        "    },\n" +
                        "    \"Orange\": {\n" +
                        "        \"Level 4\": \"Defeat Gannon\",\n" +
                        "        \"Level 5\": \"Save Princess\",\n" +
                        "        \"Level 6\": \"Find Triforce\"\n" +
                        "    }\n" +
                        "}";

                TypeReference< Map<String, HashMap<String, String>>> typeRef
                        = new TypeReference<Map<String, HashMap<String, String>>>() {
                };

                Map<String, HashMap<String, String>> value = mapper.readValue(jsonInString, typeRef);

                System.out.println(value);

            }
        }

【讨论】:

    猜你喜欢
    • 2018-03-24
    • 1970-01-01
    • 2019-08-28
    • 2019-03-01
    • 2018-07-07
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多