Creating JSON objects directly from model classes in Java

后端 未结 5 1589
一向
一向 2020-12-17 08:58

I have some model classes like Customer, Product, etc. in my project which have several fields and their setter-getter methods, I need to e

相关标签:
5条回答
  • 2020-12-17 09:12

    Google GSON does this; I've used it on several projects and it's simple and works well. It can do the translation for simple objects with no intervention, but there's a mechanism for customizing the translation (in both directions,) as well.

    Gson g = ...;
    String jsonString = g.toJson(new Customer());
    
    0 讨论(0)
  • 2020-12-17 09:15

    Use gson to achieve this. You can use following code to get the json then

    Gson gson = new Gson();
    String json = gson.toJson(yourObject);
    
    0 讨论(0)
  • 2020-12-17 09:17

    You can use Gson for that:

    Maven dependency:

    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.0</version>
    </dependency>
    

    Java code:

    Customer customer = new Customer();
    Product product = new Product();
    
    // Set your values ...
    
    Gson gson = new Gson();
    String json = gson.toJson(customer);
    
    Customer deserialized = gson.fromJson(json, Customer.class);
    
    0 讨论(0)
  •     User = new User();
        Gson gson = new Gson();
        String jsonString = gson.toJson(user);
        try {
            JSONObject request = new JSONObject(jsonString);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
    0 讨论(0)
  • 2020-12-17 09:26

    I have used XStream Parser to

        Product p = new Product();
        p.setName("FooBar Cookies");
        p.setProductType("Food");
        c.setBoughtProduct(p);
    
        XStream xstream = new XStream(new JettisonMappedXmlDriver());
        xstream.setMode(XStream.NO_REFERENCES);
        xstream.alias("p", Product.class);
        String jSONMsg=xstream.toXML(product);
        System.out.println(xstream.toXML(product));
    

    Which will give you JSON string array.

    0 讨论(0)
提交回复
热议问题