gpt4 book ai didi

java - 重新创建特定的 JSON 结构

转载 作者:行者123 更新时间:2023-11-28 17:51:12 25 4
gpt4 key购买 nike

我正在尝试在 JAVA 中重新创建以下 JSON。

[{                  
"Operation": {
Product: "MyProduct",
Noun: "MyNoun",
Verb: "MyVerb"
},
"Authentication": {
UserID: "UserName",
Password: "Password"
}}]

我觉得 Maps 是正确的选择。但是我无法形成正确的结构。

Map<String,String> opsDictionary =  new HashMap<String,String>();
opsDictionary.put("Product","MyProduct");
opsDictionary.put("Noun","MyNoun");
opsDictionary.put("Verb", "MyVerb");

Map<String,String> authDictionary = new HashMap<String,String>();
authDictionary.put("UserID","UserName");
authDictionary.put("Password", "Password");


JSONObject postdata = new JSONObject();
postdata.put("Operation", opsDictionary);
postdata.put("Authentication", authDictionary);

吐出这个不正确版本:

{
"Authentication": "{UserID=CADEMO, Password=TESTPASSORD}",
"Operation": "{Noun=User, Product=TOPSInventory, Verb=Authenticate}"
}

我玩弄了将 map 打包成一个包的想法

Bundle dataBundle = new Bundle();
dataBundle.putStringArray("Operation", opsDictionary);
dataBundle.putStringArray("Authentication", authDictionary);

我做错了什么?

我能够使用词典在我的 iOS 版本中复制这种格式。

 NSMutableDictionary * dicOperation = [[NSMutableDictionary alloc]init];
[dicOperation setValue:product forKey:@"Product"];
[dicOperation setValue:noun forKey:@"Noun"];
[dicOperation setValue:verb forKey:@"Verb"];

NSMutableDictionary * dicAuthentication = [[NSMutableDictionary alloc] init];
[dicAuthentication setValue:username forKey:@"UserID"];
[dicAuthentication setValue:password forKey:@"Password"];


NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictPackage options:NSJSONWritingPrettyPrinted error:&error];

我希望有适用于 Android 的类似解决方案。

最佳答案

您不需要使用 Hashmap。这可能是导致字符串连接结果的原因。

应该是这个

JSONObject opsDictionary = new JSONObject();
opsDictionary.put("Product","MyProduct");
opsDictionary.put("Noun","MyNoun");
opsDictionary.put("Verb", "MyVerb");


JSONObject authDictionary = new JSONObject();
authDictionary.put("UserID","UserName");
authDictionary.put("Password", "Password");


JSONObject postdata = new JSONObject();
postdata.put("Operation", opsDictionary);
postdata.put("Authentication", authDictionary);

如果您打算创建一个数组,最后附加到一个数组(在循环中或根据需要):

JSONArray ja = new JSONArray();
ja.put(postdata );

来自 How to create correct JsonArray in Java using JSONObject 的代码用法

关于java - 重新创建特定的 JSON 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35436475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com