The method add(String, JsonElement) in the type JsonObject is not applicable for the arguments (String, String)

我是研究僧i 提交于 2021-02-08 10:30:57

问题


I am trying to convert a string to JsonObject with the json.org libraray but I am getting this error:

The method add(String, JsonElement) in the type JsonObject is not applicable for the arguments (String, String)

Code:

String macAddress = wInfo.getMacAddress();  
JsonObject jsonObject = new JsonObject();
jsonObject.add("mac", macAddress);

Result should look such as the following: {"mac": "10:A5:D0:06:C6:E9"}


回答1:


to get the required result {"mac": "10:A5:D0:06:C6:E9"}, use put instead of add

JSONObject jsonObject = new JSONObject();
jsonObject.put("mac", macAddress);

instead of

jsonObject.add("mac", macAddress);



回答2:


I think I am bit late, but this answer might help others. You can have your code like below

jsonObject.add("mac", String.valueOf(macAddress));

Instead of using"put()" than "add()".




回答3:


You can use Gson

jsonObj.add("mac", new Gson().toJsonTree(macAddress));


来源:https://stackoverflow.com/questions/32200677/the-method-addstring-jsonelement-in-the-type-jsonobject-is-not-applicable-for

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!