JsonObject extract key and value in kotlin - json

In kotlin i have a response like that:
"nameIdPairs":{"name1":"590f7340a1fc", "name2":"590f7340a1fc"}}
since key and value is not determined before, it changes continuosly. Therefore, i cannot use data class. I get this response with JsonObject but i need to extract "name1" and "590f7340a1fc" seperately. What are the possible ways to do it in Kotlin?

for (key in myListTypes.keySet()) {
myListTypes.get(key).toString()
}
works for me!

Related

Dart How To parse JSON With Unique Key, Value Pairs

I am parsing a JSON object containing several key value pairs but am not sure how to make objects out of the JSON below. The keys are always different depending on the GET request so I am not able to use json['keyname'] like usual. What kind of function would I need in order to return a list of keys from 'ccwms' and a respective list of values (floats)?
{
"ccwms": {
"frc118": 160.8076758518209,
"frc1255": 15.257951313413884,
"frc1296": 11.42077882954301,
"frc7321": -161.58464745359254
}
}
After parsing the JSON, you have a normal Dart Map with string keys and some values. You can iterate maps in several ways, for example:
for (var key in map.keys) { doSomething(key, map[key]); }
for (var entry in map.entries) { doSomething(entry.key, entry.value); }
map.forEach(doSomething);
(Map.keys, Map.entries, Map.forEach).
I'm sure there are more ways to access all the keys and values.
What you do with the keys and values is up to you, it's just a map.
Minimal Dart program to convert a json string:
import 'dart:convert';
main() {
String source = """{"X":"RRRR","Y":"SSSS","ccwms": {
"frc118": 160.8076758518209,
"frc1255": 15.257951313413884,
"frc1296": 11.42077882954301,
"frc7321": -161.58464745359254
}}""";
dynamic target = JsonDecoder().convert(source);
print ( source.toString());
}
Are these keys random ? I think keys have to be predefined set, because json is a serialization for already existed object and the object structure can not be random
hope I understand correctly
should be a comment but I can not add comments right now.

How to get the key name in json?

My previous problem was I'm unable to arrange the json structure like what I wanted. And I found some answers that looks like it almost satisfy my needs but unfortunately I don't know if it's working or not because another problem has occurred.
Below, I arranged my own json data based on the json structure by someone named Programmer.
{
"dialog_type": {"human": {"inner": "He is so scary"}}
}
Here, I have a key called "human". I have two keys in my data. First is "human" and second is "non_human". Now if I have two data in my json file, it will become like this :
{
"dialog_type": {"human": {"inner": "He is so scary"}}
},
{
"dialog_type": {"non_human": "Once upon a time..."}
}
This case is maybe simillar to someone asked here. But unfortunately I have no idea if it's possible to do that in unity. I want to make a method like this answer. So I can determine what action to take by comparing those keys.
Now the question is how do I get the key name as a string in my json data using C# ?
To access the property names of a Unity javascript object, you can use:
for(var property in obj) {}
For instance, this will log all keys (i.e. property names) of all the property key-value pairs in a Unity javascript object (e.g. "key1" and "key2"):
function Start () {
var testObject = {
"key1": "value 1",
"key2": "value 2"
};
for(var property in testObject) {
Debug.Log(property.Key);
};
}
That should give you a way to check objects for any matching property names you are interested in.

Nested object JSON serialization in WebAPI

I am using .NET 4.0, MVC 4, Web API. I have following data structure:
Dictionary<Actor, Int32> TopActorToMovieCount = new Dictionary<Actor, Int32>(10);
And following entry in WebApiConfig:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
In my Controller, I am returning TopActorToMovieCount this way:
[HttpGet]
public HttpResponseMessage HighestMovies()
{
return Request.CreateResponse(HttpStatusCode.OK, MvcApplication.TopActorToMovieCount);
}
But the JSON output it is giving is:
{"api.Models.Actor":137,"api.Models.Actor":125,"api.Models.Actor":99,"api.Models.Actor":96,"api.Models.Actor":83,"api.Models.Actor":82,"api.Models.Actor":81,"api.Models.Actor":79,"....
Why it is not giving JSON structure for object of Actor?
I am sure that I am missing something, bout couldn't figure out. I tried adding following, but it didn't work:
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
PS: When I switch to XML output, it works fine.
See similar question here: Not ableTo Serialize Dictionary with Complex key using Json.net
In this case, you are using "Actor" as the Key of your dictionary. Dictionary stores key/value pairs. So when creating the JSON response, it interprets the "Actor" as a key which is converted to a string, and the "Int32" as the value thus giving you
{"api.Models.Actor":137} or {key:value}
because
Actor.ToString() would result in "api.Models.Actor"
Here's a link to the definition of Dictionary: https://msdn.microsoft.com/en-us/library/xfhwa508(v=vs.110).aspx

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.

Key Value Pair Datatype in FB 4.6

I have a JSON response form HTTP request.
"AdditionalData": {
"default" : "checked",
"example" : "empty"
}
This specific response would ideally be interoperated as a dictionary type (Key value pair). But when I auto-detect the return type of the JSON, FB 4.6 makes it of type Object. This does not work for me. For some reason the AdditionalData object in the model that I'm mapping is always null. What data type can I manually set this response to?
I don't know if you can force the result of a complex grouping to be anything but an Object when it gets returned. Once it arrives you could convert it into an ArrayCollection (of Objects or other ArrayCollections) though.