Azure / azure-documentdb-java

Java Sync SDK for SQL API of Azure Cosmos DB
MIT License
47 stars 48 forks source link

Cannot set a Date typed value to property for Document #101

Open sophiaso opened 6 years ago

sophiaso commented 6 years ago

Not sure whether this is a bug or it's a must follow rule to use the Document.

SDK version: 1.15.2

Suppose a POJO class with Date typed field:

class MyPojo {
   private String id;
   private Date date;
   // .. others omitted 
}

Create a Document and configure the property value.

   Document document = new Document();
   document.set("date", new Date()); // Exception will be thrown as Date cannot be handled, trace below
   ....

Exception trace:

A JSONObject text must begin with '{' at 1 [character 2 line 1]
   org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
   at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
   at org.json.JSONObject.(JSONObject.java:194)
   at org.json.JSONObject.(JSONObject.java:321)
   at com.microsoft.azure.documentdb.JsonSerializable.set(JsonSerializable.java:213)
moderakh commented 6 years ago

@sophiaso you can pass your custom ObjectMapper to DocumentClient. That should help in serializing your own types.

sophiaso commented 6 years ago

Hi @moderakh, thanks for providing customizable ObjectMapper, but I still do not think the JsonSerializable in 1.16.1 is able to set values for Date and Enum, and many others may exist same issue too. Could you help?

    public <T extends Object> void set(String propertyName, T value) {
        if (value == null) {
            // .... many other if else conditions omitted here for easy read purpose
        } else {
            // POJO
           // The Date time  etc. will fall into this branch, 
            try {
                this.propertyBag.put(propertyName, new JSONObject(this.getMapper().writeValueAsString(value)));
            } catch (IOException e) {
                throw new IllegalArgumentException("Can't serialize the object into the json string", e);
            }
        }
    }

this.propertyBag.put(propertyName, new JSONObject(this.getMapper().writeValueAsString(value))); For a Date typed value, even though the customized mapper will be able to process more data types than default, but the converted Date value by this.getMapper().writeValueAsString(value)) is still not a valid String to compose a JSONObject, and it should not be a JSONObject too?