我希望我的JSON看起来像这样:

{
    "information": [{
        "timestamp": "xxxx",
        "feature": "xxxx",
        "ean": 1234,
        "data": "xxxx"
    }, {
        "timestamp": "yyy",
        "feature": "yyy",
        "ean": 12345,
        "data": "yyy"
    }]
}

代码到目前为止:

import java.util.List;

public class ValueData {

    private List<ValueItems> information;

    public ValueData(){

    }

    public List<ValueItems> getInformation() {
        return information;
    }

    public void setInformation(List<ValueItems> information) {
        this.information = information;
    }

    @Override
    public String toString() {
        return String.format("{information:%s}", information);
    }

}

and

public class ValueItems {

    private String timestamp;
    private String feature;
    private int ean;
    private String data;


    public ValueItems(){

    }

    public ValueItems(String timestamp, String feature, int ean, String data){
        this.timestamp = timestamp;
        this.feature = feature;
        this.ean = ean;
        this.data = data;
    }

    public String getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }

    public String getFeature() {
        return feature;
    }

    public void setFeature(String feature) {
        this.feature = feature;
    }

    public int getEan() {
        return ean;
    }

    public void setEan(int ean) {
        this.ean = ean;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return String.format("{timestamp:%s,feature:%s,ean:%s,data:%s}", timestamp, feature, ean, data);
    }
}

我只是错过了如何用Jackson将Java对象转换为JSON的部分:

public static void main(String[] args) {
   // CONVERT THE JAVA OBJECT TO JSON HERE
    System.out.println(json);
}

我的问题是:我的课程正确吗?我必须调用哪个实例以及如何实现这个JSON输出?


当前回答

我知道这是老问题(而且我是java新手),但我遇到了同样的问题。答案对我来说不像一个新手那么清楚……所以我想补充一下我所学到的。

我使用了第三方库来帮助完成这项工作:org.codehaus.jackson 所有的下载都可以在这里找到。

对于基本JSON功能,你需要添加以下jar到你的项目库: jackson-mapper-asl 而且 jackson-core-asl

选择项目需要的版本。(通常你可以使用最新的稳定版本)。

一旦它们被导入到你的项目库中,在你的代码中添加以下导入行:

 import org.codehaus.jackson.JsonGenerationException;
 import org.codehaus.jackson.map.JsonMappingException;
 import com.fasterxml.jackson.databind.ObjectMapper;

使用java对象定义和赋值,您希望将这些值转换为JSON并作为RESTful web服务的一部分返回

User u = new User();
u.firstName = "Sample";
u.lastName = "User";
u.email = "sampleU@example.com";

ObjectMapper mapper = new ObjectMapper();
    
try {
    // convert user object to json string and return it 
    return mapper.writeValueAsString(u);
}
catch (JsonGenerationException | JsonMappingException  e) {
    // catch various errors
    e.printStackTrace();
}

结果应该是这样的: {“firstName”:“Sample”,“姓”:“用户”,“电子邮件”:“sampleU@example.com”}

其他回答

只要遵循以下任何一条:

对于杰克逊来说,这应该是可行的: ObjectMapper mapper = new ObjectMapper(); 返回mapper.writeValueAsString(对象); //返回string形式的json 对于gson,它应该工作: Gson Gson =新Gson(); 返回Response.ok (gson.toJson (yourClass)) .build ();

public class JSONConvector {

    public static String toJSON(Object object) throws JSONException, IllegalAccessException {
        String str = "";
        Class c = object.getClass();
        JSONObject jsonObject = new JSONObject();
        for (Field field : c.getDeclaredFields()) {
            field.setAccessible(true);
            String name = field.getName();
            String value = String.valueOf(field.get(object));
            jsonObject.put(name, value);
        }
        System.out.println(jsonObject.toString());
        return jsonObject.toString();
    }


    public static String toJSON(List list ) throws JSONException, IllegalAccessException {
        JSONArray jsonArray = new JSONArray();
        for (Object i : list) {
            String jstr = toJSON(i);
            JSONObject jsonObject = new JSONObject(jstr);
            jsonArray.put(jsonArray);
        }
        return jsonArray.toString();
    }
}

你可以像这样使用谷歌Gson

UserEntity user = new UserEntity();
user.setUserName("UserName");
user.setUserAge(18);

Gson gson = new Gson();
String jsonStr = gson.toJson(user);

这可能很有用:

objectMapper.writeValue(new File("c:\\employee.json"), employee);

// display to console
Object json = objectMapper.readValue(
     objectMapper.writeValueAsString(employee), Object.class);

System.out.println(objectMapper.writerWithDefaultPrettyPrinter()
     .writeValueAsString(json));

使用Jackson将对象转换为JSON:

import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.databind.ObjectWriter; 

ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);