【问题标题】:How to convert a Java Object to a JSONObject?如何将 Java 对象转换为 JSONObject?
【发布时间】:2014-08-10 22:42:45
【问题描述】:

我需要将 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();
    }

但我这次不想要文件。

【问题讨论】:

  • 它有很多库:Jackson、Jettison。您还可以将 JAXB 与 MOXy 一起使用。

标签: java android json type-conversion jsonobject


【解决方案1】:

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

SampleObject mSampleObject = new SampleObject();
String jsonInString = new Gson().toJson(mSampleObject);
JSONObject mJSONObject = new JSONObject(jsonInString);

【讨论】:

  • 我认为这是最简单、最简单、最有效的方法:)
【解决方案2】:

如果不是太复杂的对象,您可以自己做,无需任何库。下面是一个例子:

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;
    }
}

在代码中:

DemoObject demo = new DemoObject(10, "string");
JSONObject jo = demo.toJSON();

当然,如果您不介意额外的依赖,您也可以将Google Gson 用于更复杂的东西和不那么繁琐的实现。

【讨论】:

  • 我最终做了这样的事情 :)
  • 将最后一行改为 JsonObject=gson.toJson(demo) 而不是 demo.toJson()
【解决方案3】:

下面的示例几乎来自mkyongs tutorial。您可以使用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);

    }
}

【讨论】:

  • 我需要一个 Gson 库吗?
  • 是的,您需要添加 Google 的 gson 库。
【解决方案4】:

这是一种将 Java 对象转换为 JSON 对象(不是 Json 字符串)的简单方法

import com.fasterxml.jackson.databind.ObjectMapper;
import org.json.simple.parser.JSONParser;
            
JSONObject jsonObject = (JSONObject) JSONValue.parse(new ObjectMapper().writeValueAsString(JavaObject));

【讨论】:

    【解决方案5】:

    如何从 Object 中获取 JsonElement:

    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.gson.*;    
    
    final ObjectMapper objectMapper = new ObjectMapper();
    final Gson gson = new Gson();
    String json = objectMapper.writeValueAsString(source);
    JsonElement result = gson.fromJson(json, JsonElement.class);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 2013-02-23
      • 1970-01-01
      • 2017-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多