如何将Java对象转换为JSONObject?

J. *_* K. 10 java android json type-conversion jsonobject

我需要将POJO转换为JSONObject(org.json.JSONObject)

我知道如何将其转换为文件:

    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();
    }
Run Code Online (Sandbox Code Playgroud)

但这次我不想要一个文件.

小智 11

下面的例子几乎从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);

    }
}
Run Code Online (Sandbox Code Playgroud)


Phi*_*oda 7

如果它不是一个太复杂的对象,你可以自己做,没有任何库.以下是一个示例:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

在代码中:

DemoObject demo = new DemoObject(10, "string");
JSONObject jo = demo.toJSON();
Run Code Online (Sandbox Code Playgroud)

当然,如果您不介意额外的依赖性,您也可以使用Google Gson来处理更复杂的内容和不太繁琐的实现.


Vin*_*tti 5

如果我们以GSON格式解析服务器的所有模型类,那么这是将Java对象转换为JSONObject的最佳方法。在下面的代码中,SampleObject是一个Java对象,它将转换为JSONObject。

SampleObject mSampleObject = new SampleObject();
String jsonInString = new Gson().toJson(mSampleObject);
JSONObject mJSONObject = new JSONObject(jsonInString);
Run Code Online (Sandbox Code Playgroud)