0

I'm trying to create some kind of a message handler.

I will receive JSON with structure like this:

{
"data": {"Increase_A":1.5, "Increase_B":2},
"some_string": "blablabla"
}

I want to create message object in java to properly handle them.

public class Message{
    private updateField[] updateFields;
    private String some_string;

    public enum updateField{
        INCREASE_A, INCREASE_B, OTHER_ACTION;
    }
    public Message(updateField[] updateFields, String some_string){
        this.updateFields = updateFields;
        this.some_string = some_string;
    }
}

When I will receive string/json message I want to convert it to Message object.

The thing I don't know how to do is how to restrict Increase_A to integer type and Increase_B to double type. The message can contain one or more updateFields.

  • Nitpick: types in java are PascalCase. updateField -> UpdateField – Michael Sep 21 '20 at 10:53
  • @Michael thanks for this reminder! – Another Account Sep 21 '20 at 10:55
  • How do you parse JSOn in the first place? Jackson? org.json? – Polygnome Sep 21 '20 at 10:57
  • 1
    What library are you using to deserialize the JSON? Jackson? Suggest you have 2 message types which extend Message. Then you can use something like this to correctly choose the type to instantiate: https://stackoverflow.com/questions/44122782/jackson-deserialize-based-on-type – Michael Sep 21 '20 at 10:58
  • @Michael I'm using JSONObject jsonObject = new JSONObject(json_string); – Another Account Sep 21 '20 at 11:14
  • That's [org.json](https://www.baeldung.com/java-org-json) then, not sure whether there's equivalent functionality – Michael Sep 21 '20 at 11:21
  • Enum are classes which have given instances, you cannot set Integer for one and double for another for same enum class object, is this you are trying to achieve? – code_mechanic Sep 21 '20 at 12:45

0 Answers0