Currently, I am calling an API every 3 minutes to get weather data. This is the response I get as a String:
{
"data": {
"timelines": [
{
"timestep": "current",
"endTime": "2023-01-20T13:33:00-05:00",
"startTime": "2023-01-20T13:33:00-05:00",
"intervals": [
{
"startTime": "2023-01-20T13:33:00-05:00",
"values": {
"dewPoint": 18.63,
"humidity": 66,
"precipitationIntensity": 0,
"precipitationProbability": 0,
"pressureSeaLevel": 1019.19,
"pressureSurfaceLevel": 1018.65,
"temperature": 25.5,
"temperatureApparent": 25.5,
"uvIndex": 3,
"windDirection": 151.69,
"windSpeed": 4.88
}
}
]
}
]
}
}
I would like to know how to extract the value of the attributes in "values" (like "dewPoint", "humidity", etc.).
I've been trying to do this with Beans and such, but the fact that the data is nested and some of it is an array is making it difficult for me to understand.
Basically, I want to extract each of the values of the attributes in "values" from a JSON String, concat them in to an array of only the values, and then send that array to be saved in a database.
You will first need to create the classes to model this and then take the string and use an Object mapper to take a string and convert it to an object.
class WeatherData {
List<Timelines> timelines; // all other object are nested in here.
}
class Timelines {
String timestep;
String endTime;
String startTime;
List<Intervals> intervals;
}
class Intervals {
String startTime;
Values values;
}
class Values {
double dewPoint;
int humidity;
int precipitationIntensity;
int precipitationProbability;
double pressureSeaLevel;
double pressureSurfaceLevel;
double temperature;
double temperatureApparent;
int uvIndex;
double windDirection;
double windSpeed;
}
WeatherData data = new ObjectMapper().readValue(jsonString, WeatherData.class);
There are several ways to approach this once you map the json to an Object. You can loop through the values, so two for loops. Once you get to the intervals you can add the values to the array.
List<WeatherData> newWeatherDataList = new ArrayList();
The other way would be to flatten down the object so it's not so nested. I'd suggest looking up how to flatten an object in Java. You will still need one for loop to loop through the intervals array. Then just add it to the new list like above.
From here you can batch-insert the data into a table.
I hope this helps let me know if I can update the answer to provide more context.
Related
So I have two JSON files with different fields.
{
"password": { "length": 5, "reset": true},
}
"dataSettings": {
"enabled": true,
"algorithm": { "djikstra": true },
"country": { "states": {"USA": true, "Romania": false}}
}
I want to be able to use the same code to be able to print out all the nested fields and its values in the JSON.
I tried using a [JSON to Dart converter package](https://javiercbk.github.io/json_to_dart/.
However, it seems like using this would make it so I would have to hardcode all the values, since I would retrieve it by doing
item.dataSettings.country.states.USA
which is a hardcoded method of doing it. Instead I want a way to loop through all the nested values and print it out without having to write it out myself.
You can use ´dart:convert´ to convert the JSON string into an object of type Map<String, dynamic>:
import 'dart:convert';
final jsonData = "{'someKey' : 'someValue'}";
final parsedJson = jsonDecode(jsonData);
You can then iterate over this dict like any other:
parsedJson.forEach((key, value) {
// ... Do something with the key and value
));
For your use case of listing all keys and values, a recursive implementation might be most easy to implement:
void printMapContent(Map<String, dynamic> map) {
parsedJson.forEach((key, value) {
print("Key: $key");
if (value is String) {
print("Value: $value");
} else if (value is Map<String, dynamic>) {
// Recursive call
printMapContent(value);
}
));
}
But be aware that this type of recursive JSON parsing is generally not recommendable, because it is very unstructured and prone to errors. You should know what your data structure coming from the backend looks like and parse this data into well-structured objects.
There you can also perform input validation and verify the data is reasonable.
You can read up on the topic of "JSON parsing in dart", e.g. in this blog article.
I have a set of data inside a Json file that represents the GPD evolution for each country every year. I'm trying to extract this data inside a list where every year would be a dictionary inside the list.
This is a part of the Json I'm trying to work with :
{
"Name": "GPD per capita",
"Description": "Real GDP per capita in 2011US$, 2011 benchmark (suitable for cross-country growth comparisons)",
"Suffix": "$",
"Multiplier": "1",
"Data": [
{
"year": "1",
"Belgium": "1050",
"Switzerland": "1050",
"Egypt": "1225",
"Spain": "973",
"France": "1050",
"Greece": "1400",
"Iran (Islamic Republic of)": "1225",
"Iraq": "1225",
"Israel": "1225",
"Italy": "1546",
"Jordan": "1225",
"Portugal": "1050",
"Tunisia": "1225",
"Turkey": "984"
},
{
"year": "730",
"Egypt": "1278",
"Iraq": "1610",
"Japan": "633"
},
...
And this is the class where the Json file should be deserialized :
[Serializable]
public class Collection
{
public string Name;
public string Description;
public string Suffix;
public ulong Multiplier;
public List<IDictionary<string, ulong>> Data;
}
When I do Collection collection = JsonConvert.DeserializeObject<Collection>(jsonFile.ToString()); all the attributes show on the console but not the Data list.
How can I deserialize such structure correctly ?
interfaces are not (De)Serializable since the Deserializer can not know as which final actual type it should Deserialize it.
Instead of an IDictionary simply rather use an actual Dictionary
public List<Dictionary<string, ulong> Data;
Alternatively you would need to add to the JSON the actual type in order to tell the Deserializer which type shall be used for the Deserialization.
See How to automatically select a concrete type when deserializing an interface using Json.NET
I have the following Json file and I need to compare data to see how many times each value repeat itself. The problem is, I have no idea about handling Json. I don't want the answer to my exercise, I want to know how to access the data. Json:
{
"tickets": [
{
"ticket_id": 0,
"timestamp": "2016/05/26 04:47:02",
"file_hash": "c9d4e03c5632416f",
"src_ip": "6.19.128.119",
"dst_ip": "145.231.76.44"
},
{
"ticket_id": 1,
"timestamp": "2017/05/28 16:14:22",
"file_hash": "ce8a056490a3fd3c",
"src_ip": "100.139.125.30",
"dst_ip": "145.231.76.44"
},
{
"ticket_id": 2,
"timestamp": "2015/08/23 03:27:10",
"file_hash": "d17f572496f48a11",
"src_ip": "67.153.41.75",
"dst_ip": "239.168.56.243"
},
{
"ticket_id": 3,
"timestamp": "2016/02/26 14:01:33",
"file_hash": "3b28f2abc966a386",
"src_ip": "6.19.128.119",
"dst_ip": "137.164.166.84"
},
]
}
If this is a string representation of the object, first you need to set a variable and parse the string to have object you can work with.
jsonString = "{...your json string...}"
Then parse the string,
import json
jsonObject = json.loads(jsonString)
To access the data within it's like any other js object. Example :
jsonObject.tickets[0].timestamp
would return "2016/05/26 04:47:02"
tickets is the key within the jsonObject, 0 is the index of the first object in the list of tickets.
You can use the built-in "json" library to parse your file into an object:
import json
f = open('myfile.json','r')
tickets = json.loads(f.read())
This will return a "tickets" object. How you "compare" (or what exactly you compare) is up to you.
I'm new to Go and working hard to follow its style and I'm not sure how to proceed.
I want to push a JSON object to a Geckoboard leaderboard, which I believe requires the following format based on the API doc and the one for leaderboards specifically:
{
"api_key": "222f66ab58130a8ece8ccd7be57f12e2",
"data": {
"item": [
{ "label": "Bob", "value": 4, "previous_value": 6 },
{ "label": "Alice", "value": 3, "previous_value": 4 }
]
}
}
My instinct is to build a struct for the API call itself and another called Contestants, which will be nested under item. In order to use json.Marshall(Contestant1), the naming convention of my variables would not meet fmt's expectations:
// Contestant structure to nest into the API call
type Contestant struct {
label string
value int8
previous_rank int8
}
This feels incorrect. How should I configure my Contestant objects and be able to marshall them into JSON without breaking convention?
To output a proper JSON object from a structure, you have to export the fields of this structure. To do it, just capitalize the first letter of the field.
Then you can add some kind of annotations, to tell your program how to name your JSON fields :
type Contestant struct {
Label string `json:"label"`
Value int8 `json:"value"`
PreviousRank int8 `json:"previous_rank"`
}
I'm looking to create what I feel is probably a basic JSON object, but my limited knowledge of JSON is making it difficult.
I am trying to create an object that will ultimately be passed to a .NET AMSX web service. The parameter for the web service is a P1Request object, which is defined as follows:
Public Class P1RequestClause
Public Property FieldId() As Integer
Public Property OperatorId() As Integer
Public Property Value() As String
End Class
Public Class P1Request
Public Property Fields() As String()
Public Property Clauses() As P1RequestClause()
End Class
On the client side, I have a number of different form fields, the values of which I would like to wrap up in a JSON object to pass.
I am unsure of what structure my JSON object needs to match the .NET class.
Ideally my data, in psudocode, would look like:
P1Request:
Fields:
Field1,
Field2,
Field3
Clauses:
P1RequestClause:
Id1,
OpId1,
SomeValue
P1RequestClause:
Id2,
Opid2,
AnotherValue
What would this look like in JSON? It's the array of Fields in P1Request is the part that confuses me the most. As I understand JSON, it's all name:value pairs, and making an array of a single field is throwing me.
{
"Fields": [
"moo",
"says",
"the cow"
],
"Clauses": [
{
"FieldId": 1,
"OperatorId": 3,
"Value": "foo"
},
{
"FieldId": 2,
"OperatorId": 0,
"Value": "bar"
}
]
}
JSON consists of primitive types (numbers, strings, null...), objects (which are key-value pair collections), and arrays, which is what you were missing.