简体   繁体   English

如何在JsonArray(com.google.gson)中将Empty字符串转换为null

[英]How to convert Empty string to null in JsonArray ( com.google.gson)

My JSON Object has some empty values ("") So While converting it throws error. 我的JSON对象有一些空值(“”),因此在转换时会引发错误。

Here's my JSON 这是我的JSON

{
    "Animals": [
        {
            "id": 6140,
            "Name": ""
        },
        {
            "id": 6144,
            "Name": "Lion"
        }
    ]
}

My Code: 我的代码:

JsonParser parser=new JsonParser();
JsonArray myarray=parser.parse(json).getAsJsonArray();

I'm getting the error as 我收到错误信息

com.google.gson.stream.malformedjsonexception com.google.gson.stream.malformedjsonexception

How do I convert the empty string values into null while parsing the JSON object as a JSONArray? 在将JSON对象解析为JSONArray时,如何将空字符串值转换为null?

I want the final result to be 我希望最终结果是

[{id=6140, Name=null},{id=6144, Name="Lion"}] 

This is happening because the json you provided is not a json array, it is a json Object. 发生这种情况是因为您提供的json不是json数组,而是json对象。 you should do 你应该做

    JsonParser json = new JsonParser();
    JsonObject myJsonObject = json.parse(json).getAsJsonObject();
    JsonArray jsonArray = myJsonObject.getAsJsonArray("Animals");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用com.google.gson类创建json对象 - How to create json object using com.google.gson class 使用com.google.gson进行数据输入 - Data entry using com.google.gson 如何修复 Android Studio 中的“无法解析:com.google.gson:gson:2.8.5” - How to fix "Failed to resolve: com.google.gson:gson:2.8.5" in Android studio GSON - 将字符串转换为 JsonArray - GSON - convert a string into a JsonArray 如何添加com.google.gson.JsonArray的特定索引? - How to add in a specific index of com.google.gson.JsonArray? 无法使用 gson.toJson(Element) 获取 JSON 字符串,{模块 java.base 不会“打开 java.util”到模块 com.google.gson] - Can't get JSON String by using gson.toJson(Element), {module java.base does not "opens java.util" to module com.google.gson] 如何将JSONArray转换为带有Gson的List? - How to convert JSONArray to List with Gson? 为什么JsonParser使用com.google.gson API在返回值中使用双引号引起来 - Why JsonParser gives double quotes in the return value, using com.google.gson API 有两种类型:字符串和列表<Object>在 JsonArray 中,如何处理 Google Gson? - There are two types:String and List<Object> in JsonArray ,How to deal with Google Gson? java maven 导入问题:错误:com.google.gson 包不存在 - java maven import issue: error: package com.google.gson does not exist
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM