简体   繁体   中英

Gson parse regex value from json string

I receive below string from a message queue, with no double quote;

{
    tableName:STUDENT,
    columns: [{
        name: PARENT_PHONE,
        regex:{
            regexCode:PHONE,
            regexValue:[0-9\\-\\+]{9,15}
            }
        }]
}

This is the string that I try to parse it to an object as below;

TableDefinition tableDefinition = gson.fromJson(tableJson, TableDefinition.class);

Of course it's throwing an exception like;

Expected a string but was "BEGIN_ARRAY" at line ...

I understand that regexValue should start with a valid character not with [ , then I write a custom deserializer in order to parse regexValue property.

Now it is throw MalformedJsonException and debug breakpoint not even stop in custom deserializer method;

com.google.gson.stream.MalformedJsonException: Unterminated array at line 1 column 325 path $.columns[0].regex.regexValue[1]

As exception showed us, Gson still recognize regexValue as an array.

How to tell to Gson that regexValue is a string? How to deal such a situation?

You can't write a custom deserializer to a malformed JSON. If it's malformed then it's not a JSON anymore and Gson can't make any assumptions about a random string. Best bet would be to fix what is sent to the queue and if thats not doable then you would have to fix the currently-malformed-but-to-be-JSON while it's still a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM