简体   繁体   English

如何使用 gson 库将字符串转换为 JsonObject

[英]How to convert a String to JsonObject using gson library

Please advice how to convert a String to JsonObject using gson library.请建议如何使用gson库将String转换为JsonObject

What I unsuccesfully do:我不成功的做法:

String string = "abcde";
Gson gson = new Gson();
JsonObject json = new JsonObject();
json = gson.toJson(string); // Can't convert String to JsonObject

You can convert it to a JavaBean if you want using:如果您想使用,可以将其转换为 JavaBean:

 Gson gson = new GsonBuilder().setPrettyPrinting().create();
 gson.fromJson(jsonString, JavaBean.class)

To use JsonObject, which is more flexible, use the following:要使用更灵活的 JsonObject,请使用以下内容:

String json = "{\"Success\":true,\"Message\":\"Invalid access token.\"}";
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(json);
Assert.assertNotNull(jo);
Assert.assertTrue(jo.get("Success").getAsString());

Which is equivalent to the following:这相当于以下内容:

JsonElement jelem = gson.fromJson(json, JsonElement.class);
JsonObject jobj = jelem.getAsJsonObject();

要以更简单的方式做到这一点,请考虑以下内容:

JsonObject jsonObject = (new JsonParser()).parse(json).getAsJsonObject();
String string = "abcde"; // The String which Need To Be Converted
JsonObject convertedObject = new Gson().fromJson(string, JsonObject.class);

I do this, and it worked.我这样做了,并且奏效了。

You don't need to use JsonObject .您不需要使用JsonObject You should be using Gson to convert to/from JSON strings and your own Java objects.您应该使用 Gson 来转换 JSON 字符串和您自己的 Java 对象。

See the Gson User Guide :请参阅Gson 用户指南

(Serialization) (序列化)

 Gson gson = new Gson(); gson.toJson(1); // prints 1 gson.toJson("abcd"); // prints "abcd" gson.toJson(new Long(10)); // prints 10 int[] values = { 1 }; gson.toJson(values); // prints [1]

(Deserialization) (反序列化)

 int one = gson.fromJson("1", int.class); Integer one = gson.fromJson("1", Integer.class); Long one = gson.fromJson("1", Long.class); Boolean false = gson.fromJson("false", Boolean.class); String str = gson.fromJson("\\"abc\\"", String.class); String anotherStr = gson.fromJson("[\\"abc\\"]", String.class)
String emailData = {"to": "abc@abctest.com","subject":"User details","body": "The user has completed his training"
}

// Java model class
public class EmailData {
    public String to;
    public String subject;
    public String body;
}

//Final Data
Gson gson = new Gson();  
EmailData emaildata = gson.fromJson(emailData, EmailData.class);

Looks like the above answer did not answer the question completely.看起来上面的答案并没有完全回答这个问题。

I think you are looking for something like below:我认为您正在寻找以下内容:

class TransactionResponse {

   String Success, Message;
   List<Response> Response;

}

TransactionResponse = new Gson().fromJson(response, TransactionResponse.class);

where my response is something like this:我的回答是这样的:

{"Success":false,"Message":"Invalid access token.","Response":null}

As you can see, the variable name should be same as the Json string representation of the key in the key value pair.如您所见,变量名称应与键值对中键的 Json 字符串表示形式相同。 This will automatically convert your gson string to JsonObject.这将自动将您的 gson 字符串转换为 JsonObject。

Gson gson = new Gson();
YourClass yourClassObject = new YourClass();
String jsonString = gson.toJson(yourClassObject);
JsonObject jsonObject = (JsonObject) new JsonParser().parse("YourJsonString");

请注意, 从 Gson 2.8.6 开始,实例方法JsonParser.parse已被弃用并替换为静态方法JsonParser.parseString

JsonObject jsonObject = JsonParser.parseString(json).getAsJsonObject();

if you just want to convert string to json then use:如果您只想将字符串转换为 json,请使用:

use org.json: https://mvnrepository.com/artifact/org.json/json/20210307使用 org.json: https ://mvnrepository.com/artifact/org.json/json/20210307

<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20210307</version>
</dependency>

import these导入这些

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONArray;

Now convert it as现在将其转换为

//now you can convert string to array and object without having complicated maps and objects
 
try {
 JSONArray jsonArray = new JSONArray("[1,2,3,4,5]");
 //you can give entire jsonObject here 
 JSONObject jsonObject= new JSONObject("{\"name\":\"test\"}") ;
             System.out.println("outputarray: "+ jsonArray.toString(2));
             System.out.println("outputObject: "+ jsonObject.toString(2));
        }catch (JSONException err){
            System.out.println("Error: "+ err.toString());
        }

You can use the already Gson existing method:您可以使用已经存在的 Gson 方法:

inline fun <I, reified O> I.convert():O {
    val json = gson.toJson(this)
    return gson.fromJson(json, object : TypeToken<O>() {}.type)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM