0

I've searched on internet about my problem.. but I not found a good solution.

I need to get the json showed at the end:

I've 2 classes

class Order {
    Long id;

    Client client;
}

class Client {
    Long id;
}

When I serialize Order I get:

[{"id":1,"client":{"id":1}]

But I want instead to obtain:

[{"id":1,"client":1}]

How can i reach this?

Thank you for any solution!!! Marco

maba
  • 47,113
  • 10
  • 108
  • 118
gipinani
  • 14,038
  • 12
  • 56
  • 85

4 Answers4

1

- When a class implements Serializable, then its object or the object of its Sub-class are made to be Serialized.

- Now its the Fields of the Object, Not the Object itself that is being Serialized.

- And the entire object graph needs to be serialized, if not the Serialization fails.

- So Client being an Object Reference Variable in Order Class will get Serialize, and so does its Field id.

- You canNot Serialize property of a field instead of entire field, but if you want you can prevent Field from being serialized using transient keyword.

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
  • 1
    I can hardly read what you are writing. Seriously you should not overuse `code` and **bold** words. – maba Oct 04 '12 at 14:39
  • This is also my JPA domain class.. I cannot make it transient. One solution is to use @JSonIgnore on the field and use a transient getter like getClientId().. – gipinani Oct 04 '12 at 14:41
  • @mserioli...you dont need to make it transient.... that will lead to the prevention of id field to be serialized...i think you don't want that... i just mentioned it, to tell you that what you want is not possible – Kumar Vivek Mitra Oct 04 '12 at 14:42
  • Frankly i have read it online before, but never tried implementing it..... Moreover i am bit confused...whats wrong in this.. `"client":{"id":1}` This says that when the object graph was Serialized, then `an Object Reference Variable in Order class, named client of type Client which have a Field name id whose value is 1` – Kumar Vivek Mitra Oct 04 '12 at 14:50
1

Use @JsonValue annotation:

class Client {
    @JsonValue Long id;
}
StaxMan
  • 113,358
  • 34
  • 211
  • 239
0

You need to write your own serialization method for this class.

For example check this Thread: Implementing my own serialization in java

Community
  • 1
  • 1
Robin
  • 3,512
  • 10
  • 39
  • 73
0

You could also try genson library http://code.google.com/p/genson/. It has most of Jackson features and some other nice ones that jackson does not provide.

To solve your problem with genson and few code you can do it that way:

public class Order {
    Long id;
    @JsonIgnore Client client;
    @JsonProperty("client") public Long getClientId() {
        return client.id;
    }
}

public static class Client {
    Long id;
}

System.out.println(new Genson().serialize(order));

If you prefer you can also write a custom serializer with genson see here. But in your case it is not necessary.

eugen
  • 5,856
  • 2
  • 29
  • 26