I can't parse a JSON with gson - json

i have this part of my json
POKEAPI get pokemons/sprite/version/
is from POKEAPI, the problem is in kotlin I can't use the '-' for creating a variable, for example: "var myvar-i = 0" and I need to create the variables exactly like the JSON for GSON mapping and the sprites in the JSON I need are like this
generation-i
generation-ii
etc..
in kotlin, I can't create variables with the '-'
enter image description here
someone help me, ¿How can I map that information in kotlin?

You can use the annotation #SerializedName
In your case it would be something like:
class Versions {
#SerializedName("generation-i")
var generation1: Generationgame? = null
...
}
More about the annotation can be found in the docs.

Related

JSON is printed with backslashes

{"externalQueryDate":"4018-11-23"}
this is my json string, which is in a column of mysql.
I get it with creditRisk.getCreditRiskDataCodeBased()
and in javascript or in swagger, i see with backslashes:
"{\"externalQueryDate\":\"4018-11-23\"}"
I can use JSON.parse in frontend but , i want to solve this is backend.
even
for
StringWriter sw = new StringWriter();
objectMapper.writer().writeValue(sw, creditRisk.getCreditRiskDataTermBased());
it writes this:
"responseCode": "\"{\\\"externalQueryDate\\\":\\\"4018-11-23\\\"}\""
I tried those
objectMapper.readTree(creditRisk.getCreditRiskDataCodeBased()).toString()
and
objectMapper.writer().writeValue(sw, creditRisk.getCreditRiskDataTermBased());
and
#JsonRawValue
#JsonValue
How can i solve this?
In mysql, it is also without slashes
If you want to parse the json string with jackson objectMapper you need to use 'read' and tell it what class to use to create the parsed object from.
So in your case you could do something like
ObjectMapper objectMapper = new ObjectMapper();
String json = "{\"externalQueryDate\":\"4018-11-23\"}";
Map map = objectMapper.readValue(json, Map.class);
System.out.print(map.get("externalQueryDate"));
I've just used a Map here as I don't know what class you're wanting to parse the json into. If you have a class with an externalQueryDate field you can read into that. You could also use #JsonFormat on the field to tell it what the date format is if you want to parse the value straight into a LocalDate field.
I suggest you write a few simple unit tests to get the hang of escaped quotes in strings. It looks like they're causing you some confusion.

Is there a way to define a to_json handler in GDScript?

I'm new to GDScript and am looking at how best to save data to a text file. to_json works well for basic types but I just get a reference id for any custom classes. I'd ideally like to pass a dictionary of data including some custom class elements to to_json and let it convert it all at once.
Like other languages provide a toString method for printing an object, is there anything that would let me specify how a class instance should be converted to JSON?
Yeah, you would just add something like the following to your class:
func to_json():
var data = {} #must create it as a dictionary or array
data["health"] = 5
#code to create json
var json
json = data.to_json() #dictionaries automatically have this function
return json
I think it really is that simple :)
Please note: I have not tested this code.

Gson parse error, when the server response data is include an empty string(intent to be a int type), the error is Invalid double: ""

the server response data is like as
{
...
"number":"",
...
}
so when i use
Gson gson = new Gson();
gson.fromJson(data, obj.class);
the error will appear seems the String is null.
I've serach it with google and it seems custom GsonBuilder will solve this problem, but is it really and how?
Well, beacause the comment's hint, i changed my Google search wrods,and find this problementer link description here
This link will solve my problem.
So i write a primitive type typeadapter,and finally it works.
Try this, in place of "Object" use object of the class you need to convert to.
Type type= new TypeToken< Object>(){}.getType();
Object obj=new Gson().fromJson(json,type);

Why is GSON not parsing these fields properly? (FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)

I have a JSONArray of JSONObjects that I'm trying to parse with GSON. I'm using FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES. It's parsing correctly for most fields (so the FieldNamingPolicy is set correct), but I'm getting null returned for
{
"image_sq_48x48_url": "url1",
"image_sq_64x64_url": "url2",
"image_sq_96x96_url": "url3"
}
with field names
imageSq48x48Url
imageSq64x64Url
imageSq96x96Url
Maybe a better question would be what is the proper camelCase? I have also tried
imageSq48X48Url
imageSq48X48url
If I map with #SerializedName("image_sq_96x96_url") it parses/populates correctly.
Unfortunately those fieldnames in your JSON don't conform to what Gson looks for using that strategy.
If you create a POJO and serialize it, you can see what the issue is:
class MyPojo
{
String imageSq48x48Url = "hi";
}
The resulting JSON from Gson using that strategy is:
{"image_sq48x48_url":"hi"}
It doesn't consider/look at numeric digits as leading indicators / start of a "word".
If you rename the field to:
String imageSq_48x48Url;
It would work with your JSON example and that strategy.
Basically, you either need to create your own class that implements FieldNamingStrategy that will handle those JSON fieldnames the way you want, or do what you're doing with the #SerializedName annotation.

Deep JSON serialization in Grails not working

I have an object structure like so:
class Message {
static mapWith="mongo"
static embedded = ['to', 'author', 'comments', 'tags']
ObjectId id
Set<ObjectId> to
Author author
String text
List<Comment> comments
Set<String> tags
Date postedOn
Date lastEditOn
}
class Comment {
Author author
String text
int thumbsUp = 0
int thumbsDown = 0
Date postedOn
Date lastEditOn
}
And the following code for serialization to JSON
render Message.findStreamFor( session.user, groups, 0, 20 ) as JSON
However, none of the embedded collections are being serialized. They are just missing. I've tried adding the following to my Config.groovy to make it deeply serialize by default:
grails.converters.json.default.deep=true
But that doesn't seem to change anything. I've seen the objects are populated from MongoDB in the debugger, but it just doesn't make it to the JSON serialized output. How can I fix this?
UPDATE
Ok I've figured out a bit more by debugging the code. Inside the DefaultGrailsDomainClass.getPersistentProperties() it doesn't return the collections as properties when called. And JSON serializer never visits them. On line 103 of DomainClassMarshaller is the call to getPersistentProperties which isn't returning all properties.
GrailsDomainClassProperty[] properties = domainClass.getPersistentProperties();
Seems like this is a bug! How has no one else ever found this?
You could to use GSON plugin. It didn't help me in a similar problem but it may help you.
This plugin was written to overcome nested object deserialization problem in standard Grails JSON converter, but it may also be better at serializing them.