How can I deserialize a JSON array with LibGDX - json

How can I deserialize a JSON array into a Java object with libgdx? I can use the libgdx Json serialization classes to deserialize a JSON object into a Java object but I don't know how to deal with an JSON array response. Surely there is an easy way to do this?

The Array class can handle JSON arrays representations. It can be just a field of class that you want to deserialize to:
//Example of json string:
String jsonString = "{\"array\":[{\"id\":1}, {\"id\":2}, {\"id\":3}]}";
//Item class
public class Item
{
public int id;
}
//class with Array
public class ItemArray
{
public Array<Job> array;
}
//and deserialization:
... //getting JSON
Json json = new Json();
ItemArray itemArray = json.fromJson(ItemArray.class, jsonString);
If you want to use primitives please notice that there are also FloatArray and IntArray classes in LibGDX

You can always loop the json values and put it in a array yourself.
float[] elements = new float[jsonArray.get("arrayElement").size];
for (JsonValue element : jsonArray.get("arrayElement"))
{
System.out.println(element.asString());
}
Not sure how you can put the array one on one into a java array. Neither do I have the time to figure out that one.

Related

Exclude a data member from JSon serialization

This is with the Docusign Rest api. When I call ToJson() on an EnvelopeDefinition, it returns the correct info, but I would like it to not serialize the base64 array for when I am writing this out to a log file. I tried using the [JsonIgnore] directive, but that stopped the array from being serialized altogether. Do I need to override the Serialize method on this class or just create another method, something like ToJsonForLogging() and not serialize that array?
I have created an extension method that will work for you. You can call this extension method in your code as follows
string json = envelopeDefinition.ToJsonLog(logDocumentBase64:false)
I am copying the DocumentBase64 into a temporary List and then using .ToJson() function to log without the documentBase64 property.
public static class EnvelopeDefinitionExtensions
{
public static string ToJsonLog(this EnvelopeDefinition envDefinition, bool logDocumentBase64 = true)
{
if (logDocumentBase64) return envDefinition.ToJson();
var tempDocumentBase64List = new List<string>();
foreach(var doc in envDefinition.Documents)
{
tempDocumentBase64List.Add(doc.DocumentBase64);
doc.DocumentBase64 = null;
}
string json = envDefinition.ToJson();
int i =0;
foreach(var doc in envDefinition.Documents)
{
doc.DocumentBase64 = tempDocumentBase64List[i];
i++;
}
return json;
}
}

Bad saving in Unity 3D with JSON

My source code of voxel terrain can't save the data. I have a 3D char array called terrain and when I save, then it's result is empty json. The result is:
{}
The source code is:
public void TerrainSave() {
LoadingSavingClass myObject = new LoadingSavingClass();
myObject.terrain = terrain;
string json = JsonUtility.ToJson(myObject);
File.WriteAllText(Application.streamingAssetsPath + "/terrain/save.ter", json);
if(json == "{}")
{
Debug.Log("Saved clear data");
}
}
The class is:
[Serializable]
public class LoadingSavingClass
{
public char[,,] terrain = new char[128, 32, 128];
}
The saved 3D char char array isn't empty, I put some data into it before saving.
As mentioned here in JSON Serialization Docs JsonUtility.ToJson will only serialize the same types as you can serialize in Unity's inspector. char[,,,] won't serialize in Unity's inspector so it won't serialize with JsonUtility.ToJson

How does play.libs.Json.fromJson handled a List<T> in Java?

I'd like to use the Json library that comes with the play 2.1 framework.
But I'm stuck with deserializing a json object back into a java List.
With gson, you can write s.th. like
Type type = new TypeToken<List<XYZ>>(){}.getType();
List<XYZ> xyzList = gson.fromJson(jsonXyz, type);
Is there a way to do the same with play.libs.Json.fromJson ?
Any help appreciated.
Edit (17.12.2013):
I did the following to work around the problem. I guess there is a better way, but I didn't found it.
List<MyObject> response = new ArrayList<MyObject>();
Promise<WS.Response> result = WS.url(Configuration.getRestPrefix() + "myObjects").get();
WS.Response res = result.get();
JsonNode json = res.asJson();
if (json != null) {
for (JsonNode jsonNode : json) {
if (jsonNode.isArray()) {
for (JsonNode jsonNodeInner : jsonNode) {
MyObject mobj = Json.fromJson(jsonNodeInner, MyObject.class);
response.add(bst);
}
} else {
MyObject mobj = Json.fromJson(jsonNode, MyObject.class);
response.add(bst);
}
}
}
return response;
The Json library for Play Java is really just a thin wrapper over the Jackson JSON library (http://jackson.codehaus.org/). The Jackson way to deserialize a list of custom objects is mentioned here.
For your case, once you parse the json from the response body, you would do something like this, assuming MyObject is a plain POJO:
JsonNode json = res.asJson();
try{
List<MyObject> objects = new ObjectMapper().readValue(json, new TypeReference<List<MyObject>>(){});
}catch(Exception e){
//handle exception
}
I'm assuming you were asking about Play Java based on your edit, Play Scala's JSON library is also based on Jackson but has more features and syntactic sugar to accommodate functional programming patterns.
You can use the following code:
List<YourClass> returnedRoles = new ObjectMapper().readValue(jsonString
,TypeFactory.defaultInstance().constructCollectionType(List.class,
YourClass.class));

GWT HashMap to/from JSON

I might be getting a bit tired tonight but here it goes:
I'd like to have GWT HashMap to/from JSON. How would I achieve this?
In other words, I'd like to take an HashMap, take its JSON representation, store it somewhere and get it back to its native Java representation.
Here is my quick solution:
public static String toJson(Map<String, String> map) {
String json = "";
if (map != null && !map.isEmpty()) {
JSONObject jsonObj = new JSONObject();
for (Map.Entry<String, String> entry: map.entrySet()) {
jsonObj.put(entry.getKey(), new JSONString(entry.getValue()));
}
json = jsonObj.toString();
}
return json;
}
public static Map<String, String> toMap(String jsonStr) {
Map<String, String> map = new HashMap<String, String>();
JSONValue parsed = JSONParser.parseStrict(jsonStr);
JSONObject jsonObj = parsed.isObject();
if (jsonObj != null) {
for (String key : jsonObj.keySet()) {
map.put(key, jsonObj.get(key).isString().stringValue());
}
}
return map;
}
Not the most optimized, but should be easy to code: use JSONObject.
Iterate over your map's entries and put them in a JSONObject (converting each value to a JSONValue of the appropriate type), then call toString to get the JSON representation.
For parsing, get a JSONObject back using a JSONParser, then iterate over the keySet, geting the values and putting them in your map (after unwrapping the JSONValues)
But beware of the keys you use! You cannot use any kind of key as a property name in JS; and JSON processing in the browser always involve going through a JS object (or implementing the JSON parser yourself, which won't perform the same)

Creating a JSON object in MonoTouch (C#)

How do i manually create a JSON object in monotouch(4.0)?
The System.JSON namespace is available, (JsonObject, JsonArray, jSonPrimitive and JsonValue) but those are all abstract, so i can't just do this :
JsonObject myObject = new JsonObject();
I need to manually build a JSON object, and do not want to use DataContractSerialisation.
For reference purposes :
-I will need to transfer that JSON object to a server with a web call later. (but i can handle that part)
Use JSON.net http://json.codeplex.com/
As it turns out, after a long time of trying and searching ; only the JsonPrimitiveconstructor and the JsonObject constructor can be used.
JsonPrimitive and JsonValue can both be cast to JsonValue.
the JsonObject requires a KeyValuePair<string, JsonValue>
if i define functions like this :
public static KeyValuePair<String, JsonValue> IntRequired(string key, int val)
{
return new KeyValuePair<String, JsonValue>(key, new JsonPrimitive(val));
}
i can create a json object like this :
JSonObject myObject = new JsonObject();
myObject.add(new IntRequired("id",1));