GSON中JsonElement节点的toString()与getAsString()的区别

本文介绍了GSON中JsonElement的toString()和getAsString()两个方法的区别。使用区别在于,toString()返回带双引号的JsonElement字符串表示,而getAsString()返回的是不带双引号的字符串值。如果调用getAsString()时,JsonElement不是JsonPrimitive、String或单元素JsonArray,将抛出UnsupportedOperationException。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、使用区别

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;

public class GsonTest {

    public static void main(String[] args) {
        JsonElement jsonElement = new JsonPrimitive("foo");

        System.out.println(jsonElement.toString());
        System.out.println(jsonElement.getAsString());

        jsonElement = new JsonPrimitive(42);

        System.out.println(jsonElement.toString());
        System.out.println(jsonElement.getAsString());

        jsonElement = new JsonPrimitive(true);

        System.out.println(jsonElement.toString());
        System.out.println(jsonElement.getAsString());

        jsonElement = new JsonObject();
        ((JsonObject) jsonElement).addProperty("foo", "bar");
        ((JsonObject) jsonElement).addProperty("foo2", 42);

        System.out.println(jsonElement.toString());
        System.out.println(jsonElement.getAsString());
    }
}

“foo”
foo
42
42
true
true
{“foo”:“bar”,“foo2”:42}
Exception in thread “main” java.lang.UnsupportedOperationException: JsonObject
at com.google.gson.JsonElement.getAsString(JsonElement.java:185)

二、源码分析

toString源码

 /**
   * Returns a String representation of this element.
   */
  @Override
  public String toString() {
    try {
      StringWriter stringWriter = new StringWriter();
      JsonWriter jsonWriter = new JsonWriter(stringWriter);
      jsonWriter.setLenient(true);
      Streams.write(this, jsonWriter);
      return stringWriter.toString();
    } catch (IOException e) {
      throw new AssertionError(e);
    }
  }

getAsString源码

  /**
   * convenience method to get this element as a string value.
   *
   * @return get this element as a string value.
   * @throws ClassCastException if the element is of not a {@link JsonPrimitive} and is not a valid
   * string value.
   * @throws IllegalStateException if the element is of the type {@link JsonArray} but contains
   * more than a single element.
   */
  public String getAsString() {
    throw new UnsupportedOperationException(getClass().getSimpleName());
  }

由上述可知:

  • toString()返回的是JsonElement的字符串,所有是带双引号的,eg: “foo”;getAsString()返回的是JsonElement的字符串值,所以不带双引号,eg:foot
  • getAsString的入参不是以下类型:JsonPrimitive类型、String类型或者只包含单个元素的JsonArray类型,就会抛出异常;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值