创建JSON对象并将其转换为Java中的String [英] Create JSON object and convert it to String in Java
问题描述
我需要通过http帖子发送一个相当长的JSON头。在Python中是这样的:
I need to send a quite long JSON header through an http post. In Python was like this:
self.body_header = {
"client": self.client_name,
"clientRevision": self.client_version,
"uuid": str(uuid.uuid4()),
"session": self.get_sessionid()}
self.body = {
"header": self.body_header,
"country": {"IPR":"1021", "ID":"223", "CC1":"0", "CC2":"0", "CC3":"0", "CC4":"2147483648"},
"privacy": 1}
我需要在Java中做类似的事情,即以某种方式创建一个JSON结构,将其转换为String并通过http发送它。
I need to do something similar in Java, ie, create somehow a JSON struct, convert it to a String and send it via http.
问题是,我怎样才能轻松实现这一目标?有用的库吗?我知道如何发送它,但不知道如何构建它然后创建一个字符串。
The question is, how can I achieve that easily? Any useful libraries? I know how to send it, but not how to build it and then create a String.
谢谢大家。
推荐答案
您可以使用 gson 。
你可以创建一个Java对象(POJO)并将其序列化为JSON:
You can create a Java Object (POJO) and serialize it as JSON by doing:
Gson gson = new Gson();
String json = gson.toJson(yourObject);
然后您可以通过HTTP发送字符串。
You can then send the string over HTTP.
如果你不想去POJO路线,你仍然可以使用 JsonElement , JsonArray , JsonObject 。
If you do not want to go the POJO route, you can still create the JSON struct using JsonElement, JsonArray, JsonObject in the Gson API.
这篇关于创建JSON对象并将其转换为Java中的String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!