[System.Serializable]
public class JsonObjects
{
public List<Levels> levels;
}
[System.Serializable]
public class Levels
{
public List<string> level_data;
}
deserialization:
objects = JsonUtility.FromJson<JsonObjects>(jsonFile.text);
List<Levels> levels = objects.levels;
How to make level_data accesible? I want to go through level data list and get the coordinates into vector2
level_data list is situated in the levels list
List<string> levelData0= levels[0].level_data; // [ "50", "50", "950"...
List<string> levelData1= levels[1].level_data; // [ "500", "80", "652",...
Related
i don't know if I'm explaining it right but what i want is to be able to save 3 lists of strings but have them separated based on time. The idea is to store some strings for each day and save them into a json so i can search for the date and display them into a calendar.
My try was like so
[Serializable]
public class TimeStamp
{
public string CreatedDate;
public List<Entries> day = new List<Entries>();
}
[Serializable]
public class Entries
{
public List<string> names = new List<string>();
public List<string> location = new List<string>();
public List<string> info = new List<string>();
}
which then i saved like so
string json = JsonUtility.ToJson(timeStamp);
try
{
timeStamp.CreatedDate = DateTime.UtcNow.ToLocalTime().ToString("dd-MM-yyyy HH:mm");
File.WriteAllText(Application.persistentDataPath + "/Journal.json", json);
Debug.Log("Data Saved");
}
catch (Exception e)
{
Debug.Log("Error Saving Data:" + e);
throw;
}
Which does save everything i need but its not separated by the date, trying to explain it the way i think of it is that i want the date to be the "header" of the Json so in one Json file i would have all entries for each day and also i made them into a list so i can add or remove strings.
So later on when i want to add something i would search for the date and access the names list for instance and .Add() my string to that list
In a rather crude way this is how i would like my json to look like:
entries
[
"date"[
list1 = []
list2 = []
list3 = []
]
]
The way i feel like it should be is something like this
[Serializable]
public class Roots
{
public TimeStamp timeStamp;
}
[Serializable]
public class TimeStamp
{
public List<Entries> entries;
}
[Serializable]
public class Entries
{
public List<string> names = new List<string>();
public List<string> location = new List<string>();
public List<string> info = new List<string>();
}
which gives a json like this
{
"Entries": {
"Timestamp": [
{
"names": "",
"location": "",
"info": ""
}
]
}
}
but how can i make that Timestamp be a string or a date?
I guess you actually rather want to have a collection class like
[Serializable]
public class Root
{
public List<TimeStamp> timestamps = new List<TimeStamp>();
}
and rather add your individual timestamps to that list e.g.
// Probably you would load this from JSON at start of your app
private Root root = new Root();
...
root.timeStamps.Add(new TimeStamp(...));
And then
string json = JsonnUtility.ToJson(root);
...
So just the way you already have with
[Serializable]
public class TimeStamp
{
public string CreatedDate;
public List<Entries> day = new List<Entries>();
}
[Serializable]
public class Entries
{
public List<string> names = new List<string>();
public List<string> location = new List<string>();
public List<string> info = new List<string>();
}
This should give you a JSON looking like
{
"timestamps" :
[
{
"CreatedDate" : "12-04-2021 12:34",
"day" :
[
{
"names" : ["Guy1", "Dude2", "Jack3"],
"location" : ["Room1", "Place2", "Location3"],
"info" : ["This", "is", "some", "info"]
},
{
"names" : [...],
"location" : [...],
"info" : [...]
},
...
]
},
{
"CreatedDate" : "13-07-2021 14:42",
"day" :
[
{
"names" : [...],
"location" : [...],
"info" : [...]
},
...
]
},
...
]
}
If your goal was rather to actually have something like
{
"timestamps" :
[
{
"12-04-2021 12:34":
{
[
{
"names" : ["Guy1", "Dude2", "Jack3"],
"location" : ["Room1", "Place2", "Location3"],
"info" : ["This", "is", "some", "info"]
},
...
]
}
},
{
"13-07-2021 14:42" :
{
[
{
"names" : [...],
"location" : [...],
"info" : [...]
},
...
]
}
},
...
]
}
then you will need to rather use soemthing like
[Serializable]
public class Root
{
public Dictionary<string, List<Entries>> timestamps = new Dictionary<string, List<Entries>>();
}
[Serializable]
public class Entries
{
public List<string> names = new List<string>();
public List<string> location = new List<string>();
public List<string> info = new List<string>();
}
but this is not supported by the built-in JsonUtility and you would rather need to use e.g. Newtonsoft JSON.NET (which is available as a Unity Package) and see in particular Serializing a Dictionary
I've the following Json response coming from a Feign client:
{
"maxResults": 1,
"total": 5,
"isLast": false,
"values": [
{
"id": 37,
"self": "https://your-domain.atlassian.net/rest/agile/1.0/sprint/23",
"state": "active",
"name": "sprint 1",
"goal": "sprint 1 goal"
}
]
}
The feign client:
#FeignClient(name = "jira")
public interface JiraFeignClient {
#GetMapping("/rest/agile/1.0/board/{boardId}/sprint?state=active&maxResults=1")
ActiveSprintResponse getActiveSprint(#PathVariable String boardId);
}
I'd like to define the ActiveSprintResponse class in order to have the information related to the "values" property (I'm only interested in those) of the json response but I don't understand how can I easily represent it.
I would have no problems for the properties "maxResults", "total" etc... but how can easily unpack "values"? I can assume I will always have only one element in the value array.
I've tried defining it like that but it clearly does not work:
public class ActiveSprintResponse {
private final String id;
private final String self;
private final String name;
private final String goal;
public ActiveSprintResponse(String id, String self, String name, String goal) {
this.id = id;
this.self = self;
this.name = name;
this.goal = goal;
}
}
You need to define a class that represents the root JSON object. You can define a property for the values of type List then:
public class ActiveSprintResponseList {
private List<ActiveSprintResponse> values;
// (Other fields omitted for simplicity)
public void setValues(List<ActiveSprintResponse> values) {
this.values = values;
}
public List<ActiveSprintResponse> getValues() {
return values;
}
}
you then need to declare that class as return type:
#FeignClient(name = "jira")
public interface JiraFeignClient {
#GetMapping("/rest/agile/1.0/board/{boardId}/sprint?state=active&maxResults=1")
ActiveSprintResponseList getActiveSprint(#PathVariable String boardId);
}
and use it on the calling side:
ActiveSprintResponseList response = client.getActiveSprint(..);
List<ActiveSprintResponse> values = response.getValues();
// work with values
I have been trying to deserialize the data received from this API:
{
"result": "success",
"timestamp": 1521038012878,
"data": {
"GB": 14,
"DE": 2,
"US": 2
},
"totalIsPublic": true,
"advanced": false,
"totalDownloads": {
"GB": 14,
"DE": 2,
"US": 2
}
}
Here is the POJO class:
public class BintrayDownloadCounts {
private List<Integer> totalDownloads = new ArrayList<>();
#JsonProperty("totalDownloads")
public List<Integer> getTotalDownloads() {
return totalDownloads;
}
public void setTotalDownloads(List<Integer> totalDownloads) {
this.totalDownloads = totalDownloads;
}
}
When I tried deserializing using :
downloadCounts = mapper.readValue(json, BintrayDownloadCounts.class);
I get this error:
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.Integer out of START_OBJECT token
I have seen many questions containing this error but I am unable to figure out a solution for this particular use case. It may be noted that the totalDownloads object is dynamic i.e. its contents are not constant.
The totalDownloads property is not an array, so it cannot be mapped to a List<Integer>. Use Map<String, Integer> instead and ensure that you tell Jackson to ignore the properties that are not mapped to avoid mapping errors:
#JsonIgnoreProperties(ignoreUnknown = true)
public class BintrayDownloadCounts {
#JsonProperty("totalDownloads")
private Map<String, Integer> totalDownloads;
public Map<String, Integer> getTotalDownloads() {
return totalDownloads;
}
public void setTotalDownloads(Map<String, Integer> totalDownloads) {
this.totalDownloads = totalDownloads;
}
}
Then you are good to go:
ObjectMapper mapper = new ObjectMapper();
BintrayDownloadCounts downloadCounts = mapper.readValue(json, BintrayDownloadCounts.class);
i need to consume a RESTApi, which gives me a JSON output like this
{
"id": "e5d5ccc0-8da4-430d-b0ec-096d17ae2af8",
"car": [
{
"identifier": "XX000YY",
"formattedAddress": "Address 1",
"lat": 45.841664,
"lng": 18.199905,
"isOn": false,
"odometer": 763.4,
}
],
"location": "92589f4a-8c6e-4494-8548-b5428f8fa598"
}
Usually i would create a Wrapper Object
public class Wrapper{
private String id;
private Car car;
private String location;
//getters and setters
}
Then in my controller i would do something like this
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Wrapper> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity,wrapper);
to get the response
But basically i need only the Car object, so i was thinking if there was a way to just return the it instead of the whole wrapper and taking the Car objects from it
First of all, you must create a serializable object like this :
Car.java
package com.wrapper;
public class Car implements Serializable{
public String identifier;
public String formattedAddress;
public Float lat;
public Float lng;
public Boolean isOn;
public Float odometer;
}
Wrapper.java
package com.wrapper;
import java.util.List;
public class Wrapper implements Serializable{
public String id;
public List<Car> car = null;
public String location;
}
After that, use a google API gson and use this instruction to get an object :
Wrapper wrapper = gson.fromJson(response, Wrapper.class);
If my response is like:
{
"values": [ "1", "2" ]
}
How should I use readEntity to populate a List<String> with the values: 1, 2?
You can read the entity as a Map<String, List<String>>:
Map<String, List<String>> map =
response.readEntity(new GenericType<Map<String, List<String>>>() { });
List<String> values = map.get("values");
Or define your own POJO:
public class MyBean {
private List<String> values;
// Getters and setters
}
List<String> values = response.readEntity(MyBean.class).getValues();
You obviously must have a JSON provider such as Jackson registered.