gson string转json_string转换成jsonobject

gson string转json_string转换成jsonobjectCan’tseemtofigurethisout.似乎无法弄清楚。I’mattemptingJSONtreemanipulationinGSON,butIhavea

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

本文翻译自:Gson: Directly convert String to JsonObject (no POJO)

Can’t seem to figure this out. 似乎无法弄清楚。 I’m attempting JSON tree manipulation in GSON, but I have a case where I do not know or have a POJO to convert a string into, prior to converting to JsonObject . 我正在尝试在GSON中进行JSON树操作,但是在转换为JsonObject之前,我不知道或没有POJO将字符串转换成这种情况。 Is there a way to go directly from a String to JsonObject ? 有没有一种方法可以直接从String转到JsonObject

I’ve tried the following (Scala syntax): 我已经尝试了以下(Scala语法):

val gson = (new GsonBuilder).create

val a: JsonObject = gson.toJsonTree("""{ "a": "A", "b": true }""").getAsJsonObject
val b: JsonObject = gson.fromJson("""{ "a": "A", "b": true }""", classOf[JsonObject])

but a fails, the JSON is escaped and parsed as a JsonString only, and b returns an empty JsonObject . 但是a失败,仅将JSON逸出并解析为JsonStringb返回一个空的JsonObject

Any ideas? 有任何想法吗?


#1楼

参考:https://stackoom.com/question/hfn2/Gson-直接将String转换为JsonObject-无POJO


#2楼

String jsonStr = "{\"a\": \"A\"}";

Gson gson = new Gson();
JsonElement element = gson.fromJson (jsonStr, JsonElement.class);
JsonObject jsonObj = element.getAsJsonObject();

#3楼

Came across a scenario with remote sorting of data store in EXTJS 4.X where the string is sent to the server as a JSON array (of only 1 object). 遇到了一种在EXTJS 4.X中对数据存储进行远程排序的情况,其中该字符串作为JSON数组(只有1个对象)发送到服务器。
Similar approach to what is presented previously for a simple string, just need conversion to JsonArray first prior to JsonObject. 与之前针对简单字符串提供的方法类似,只需要在JsonObject之前先转换为JsonArray。

String from client: [{“property”:”COLUMN_NAME”,”direction”:”ASC”}] 来自客户的字符串: [{“ property”:“ COLUMN_NAME”,“ direction”:“ ASC”}]

String jsonIn = "[{\"property\":\"COLUMN_NAME\",\"direction\":\"ASC\"}]";
JsonArray o = (JsonArray)new JsonParser().parse(jsonIn);

String sortColumn = o.get(0).getAsJsonObject().get("property").getAsString());
String sortDirection = o.get(0).getAsJsonObject().get("direction").getAsString());

#4楼

The simplest way is to use the JsonPrimitive class, which derives from JsonElement , as shown below: 最简单的方法是使用从JsonElement派生的JsonPrimitive类,如下所示:

JsonElement element = new JsonPrimitive(yourString);
JsonObject result = element.getAsJsonObject();

#5楼

I believe this is a more easy approach: 我相信这是一个更简单的方法:

public class HibernateProxyTypeAdapter implements JsonSerializer<HibernateProxy>{

    public JsonElement serialize(HibernateProxy object_,
        Type type_,
        JsonSerializationContext context_) {
        return new GsonBuilder().create().toJsonTree(initializeAndUnproxy(object_)).getAsJsonObject();
        // that will convert enum object to its ordinal value and convert it to json element

    }

    public static <T> T initializeAndUnproxy(T entity) {
        if (entity == null) {
            throw new 
               NullPointerException("Entity passed for initialization is null");
        }

        Hibernate.initialize(entity);
        if (entity instanceof HibernateProxy) {
            entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer()
                    .getImplementation();
        }
        return entity;
    }
}

And then you will be able to call it like this: 然后您将可以这样调用它:

Gson gson = new GsonBuilder()
        .registerTypeHierarchyAdapter(HibernateProxy.class, new HibernateProxyTypeAdapter())
        .create();

This way all the hibernate objects will be converted automatically. 这样,所有休眠对象将自动转换。


#6楼

//import com.google.gson.JsonObject;  
JsonObject complaint = new JsonObject();
complaint.addProperty("key", "value");
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/172479.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • springboot启动时是如何加载配置文件application.yml文件

    springboot启动时是如何加载配置文件application.yml文件今天启动springboot时,明明在resources目录下面配置了application.yml的文件,但是却读不出来,无奈看了下源码,总结一下springboot查找配置文件路径的过程,能力有限,欢迎各位大牛指导!!!spring加载配置文件是通过listener监视器实现的,在springboot启动时:在容器启动完成后会广播一个SpringApplicationEvent事件,而Spri…

    2022年9月6日
    5
  • ubuntu-cuda卸载[通俗易懂]

    ubuntu-cuda卸载[通俗易懂]不小心用sudoaptuninstallnvidia-cuda-toolkit安装了cuda,安装的是7.5发现,卸载sudoapt-getremove–auto-removenvidia-cuda-toolkit

    2025年9月17日
    6
  • 华为光纤交换机zone配置

    华为光纤交换机zone配置需求:划分2个zone,接入两个不同业务群集。环境:华为光纤交换机SNS2124IOIO:串口,只用于串口登录admin/Hawei12#$有网络图标的口:管理口,管理地址10.77.77.77,http://10.77.77.77admin/Hawei12#$,连接网线可通过ssh登录。使用ipaddrset命令修改地址。注意:按照第一步至第六步即可完成配置,如修过别名或zone成…

    2022年5月11日
    296
  • PXE部署

    PXE部署笑洋仟博客园首页新随笔联系订阅管理随笔-51文章-0评论-0阅读-2177PXE高效批量网络装机阅读目录(Content)一、PXE概述 1、PXE(PrebooteXcutionEnvironment)的概念 2、PXE批量部署的优点 3、部署PXE远程安装服务 4、搭建PXE远程安装服务器 二、搭建PXE远程安装服务器的步骤 1、安装启用TFTP服务 2、安装启用DHCP服务  …

    2022年6月29日
    25
  • layui弹框传值_LAYUI弹出层详解

    layui弹框传值_LAYUI弹出层详解还是一步步展示把首先,layer可以独立使用,也可以通过Layui模块化使用。我个人一直是用的模块化的所以下面素有的都是基于模块化的。引入好相关文件就可以开始啦今天放图片把试着学一下放图片1.最简单的弹层,这个弹层的效果其实就是一个加了特效和样式的alert();代码如下:layui.use(“layer”,function(){varlayer=layui.layer;la…

    2022年6月1日
    88
  • vim学习六之搜索命令「建议收藏」

    vim学习六之搜索命令「建议收藏」目录Vim基本搜索命令/或者?搜索n/N正反向下一个特殊搜索Vim高亮搜索搜索大小写敏感搜索进阶Vim正则表达式搜索查找在行首的特定串查找在行尾的特定串匹配特定行Vim基本搜索命令/或者?搜索在Vim普通模式下,输入/或?符号就进入了搜索模式,/用于正向往下搜索,?用于反向往上搜索。n/N正反向下一个在搜索模式下可以对Vim打开的整个文本内容进行搜索,当按下n时可以继续正向查找下一个相匹配的目前单词。N的作用与n相反,是往上反向搜索目标单词。特殊搜索在Vim命

    2022年9月23日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号