Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to create model with dynamic json fieldname #177

Open
afomich opened this issue Sep 6, 2016 · 2 comments
Open

How to create model with dynamic json fieldname #177

afomich opened this issue Sep 6, 2016 · 2 comments

Comments

@afomich
Copy link

afomich commented Sep 6, 2016

Hello everybody.

I'm new in LoganSquare, and i'm faced with next problem.
I have next json structure:
{
"status": "ok", -> String
"meta": { -> Model with integer value
"count": 1
},
"data": { -> Model with child JSON object
"1466466": { <------ Dynamic name
"field1": "value1",
"field2": value2,
"field3": value3
}
}
}, where "1466466" is filed with dynamic key. How I can parse it?
Thanks.

@mannodermaus
Copy link
Contributor

My initial reaction to this situation would be to map your data field to a Map<String, Fields> object, where Fields is a @JsonObject class containing your field1 to field3 stuff. Then, you'd expose some more convenient accessors to those fields based on the keySet() of that Map:

@JsonObject
class Outer {
    @JsonField(name = "status")
    String status;

    @JsonField(name = "meta")
    Meta meta;

    @JsonField(name = "data")
    Map<String, Fields> data;

    // ...

    public String getField1() {
        // Of course, you probably want to check for "empty" first, this is just the basic idea
        return data.keySet().get(0).getField1();
    }
}

@JsonObject
class Fields {
    @JsonField(name = "field1")
    String field1;

    // ...
}

@afomich
Copy link
Author

afomich commented Sep 9, 2016

Thanks a lot!
A found the similar solution with TreeMap and this works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants