7

As the title describes I'm trying to assign a json string to my class, but the json string will presumably contain several variables which I have not created in the class they are being assigned to.

To show you first what works, I have

    ObjectMapper mapper = new ObjectMapper();

    try {

        Tweet tweet1 = mapper
                .readValue(
                        "{\"created_at\":\"Sat Feb 08 11:26:02 +0000 2014\"}",
                        Tweet.class);

    } catch (JsonMappingException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

That works, as the class, Tweet, has the variable "created_at" with getter and setter methods all in place.

Like mentioned though, I need to expect the string in the readValue method to contain things which are not to be found in my Tweet class.

To get around this, I import and use:

    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

Which theoretically helps me avoid all the unknowns in there, and just assigns the values that are to be found in the Tweet class.

So, I add a value which is not to be found in Tweet, like so:

    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    try {

        Tweet tweet1 = mapper
                .readValue(
                        "{\"created_at\":\"Sat Feb 08 11:26:02 +0000 2014\",\"id\":432113085571407872\"}",
                        Tweet.class);

    } catch (JsonMappingException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

Now, the value "id" does not exist in my Tweet class, and should therefor be ignored (no?).

But, now the console throws me an error:

com.fasterxml.jackson.core.JsonParseException: Unexpected character ('"' (code 34)): was expecting comma to separate OBJECT entries at [Source: java.io.StringReader@7817ea54; line: 1, column: 72]

Now this makes me a sad panda, because I cannot for the life of me understand what it is I'm doing wrong.

Anyone with better eyes and/or a sharper mind than mine, see my mistake?

Or am I going about this all wrong?

1 Answer 1

7

Your JSON is invalid. Here's the value of the id attribute:

432113085571407872\"

You see that either it has a quote missing at the beginning, or it has a quote that shouldn't be there at the end.

That's what the error message says, BTW:

Unexpected character ('"'

Sign up to request clarification or add additional context in comments.

1 Comment

Dammit, was it that simple? I swear, I need new glasses. Thanks though, I'll make your answer the correct one!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.