Java JsonObject数组的键值 [英] Java JsonObject array value to key

查看:790
本文介绍了Java JsonObject数组的键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的新手,所以这有点令人困惑

我想获取json格式的字符串

我想要的结果是

{ "user": [ "name", "lamis" ] }

我当前正在做的是这样:

JSONObject json = new JSONObject();         
json.put("name", "Lamis");
System.out.println(json.toString());

我得到这个结果

{"name":"Lamis"}

我尝试了这个,但是没有用 json.put("user",json.put("name","Lamis")))

解决方案

尝试一下:

JSONObject json = new JSONObject();         
json.put("user", new JSONArray(new Object[] { "name", "Lamis"} ));
System.out.println(json.toString());

但是,您显示的错误"结果比正确"结果更自然地映射了存在具有 name 名称"的用户"lamis". /p>

为什么您认为正确"结果更好?

I'm new to java so this is a bit confusing

I want to get json formatted string

The result I want is

{ "user": [ "name", "lamis" ] }

What I'm currently doing is this :

JSONObject json = new JSONObject();         
json.put("name", "Lamis");
System.out.println(json.toString());

And I'm getting this result

{"name":"Lamis"}

I tried this but it didnt work json.put("user", json.put("name", "Lamis"));

解决方案

Try this:

JSONObject json = new JSONObject();         
json.put("user", new JSONArray(new Object[] { "name", "Lamis"} ));
System.out.println(json.toString());

However the "wrong" result you showed would be a more natural mapping of "there's a user with the name "lamis" than the "correct" result.

Why do you think the "correct" result is better?

这篇关于Java JsonObject数组的键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆