如何将 Java 对象转换为 JSONObject?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24322776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a Java Object to a JSONObject?
提问by J. K.
i need to convert a POJO to a JSONObject (org.json.JSONObject)
我需要将 POJO 转换为 JSONObject (org.json.JSONObject)
I know how to convert it to a file:
我知道如何将其转换为文件:
ObjectMapper mapper = new ObjectMapper();
try {
mapper.writeValue(new File(file.toString()), registrationData);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
But I dont want a file this time.
但这次我不想要文件。
采纳答案by Philipp Jahoda
If it's not a too complex object, you can do it yourself, without any libraries. Here is an example how:
如果不是太复杂的对象,你可以自己做,不需要任何库。下面是一个例子:
public class DemoObject {
private int mSomeInt;
private String mSomeString;
public DemoObject(int i, String s) {
mSomeInt = i;
mSomeString = s;
}
//... other stuff
public JSONObject toJSON() {
JSONObject jo = new JSONObject();
jo.put("integer", mSomeInt);
jo.put("string", mSomeString);
return jo;
}
}
In code:
在代码中:
DemoObject demo = new DemoObject(10, "string");
JSONObject jo = demo.toJSON();
Of course you can also use Google Gsonfor more complex stuff and a less cumbersome implementation if you don't mind the extra dependency.
当然,如果您不介意额外的依赖,您也可以将Google Gson用于更复杂的东西和不那么麻烦的实现。
回答by Philipp Jahoda
The example below was pretty much lifted from mkyongs tutorial. Instead of saving to a file you can just use the String json
as a json representation of your POJO.
下面的示例几乎取自mkyongs 教程。您可以将String json
用作 POJO 的 json 表示,而不是保存到文件中。
import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.Gson;
public class GsonExample {
public static void main(String[] args) {
YourObject obj = new YourOBject();
Gson gson = new Gson();
String json = gson.toJson(obj); //convert
System.out.println(json);
}
}
回答by Vinod Pattanshetti
If we are parsing all model classes of server in GSON format then this is a best way to convert java object to JSONObject.In below code SampleObject is a java object which gets converted to the JSONObject.
如果我们以 GSON 格式解析服务器的所有模型类,那么这是将 java 对象转换为 JSONObject 的最佳方法。在下面的代码中,SampleObject 是一个转换为 JSONObject 的 java 对象。
SampleObject mSampleObject = new SampleObject();
String jsonInString = new Gson().toJson(mSampleObject);
JSONObject mJSONObject = new JSONObject(jsonInString);