Reputation: 3
I'm trying to combine multiple JSON objects into one JSON array and maybe filter on the name of the data (temperature, pressure, altitude).
I tried to use JSON-Simple and Java but I can't get it to work.
Here are the pieces of JSON:
The input I want to convert:
{"temperature" : -12, "sendtimes" : 10000}
{"pressure" : 1000, "sendtimes" : 10001}
{"altitude" : 100.7, "sendtimes" : 10002}`
How I want it after conversion:
{
"temperaturData": [
{"temperature": -12, "sendtimes": 10000},
{"pressure" : 1000, "sendtimes" : 10001},
{"altitude" : 100.7, "sendtimes" : 10002},
]
}
I have no clue on how to do this, thanks to everyone who can help me!
Upvotes: 0
Views: 4712
Reputation: 7808
JSON Library mentioned by Jatin Asija is a very cool and simple JSON library that you efinitely can use to get what you want. However the de-facto standard for working with JSON in java is Jackson JSON library also known as "FasterXML/jackson". All you will have to do is to use ObjectMapper
class and its methods readValue()
and writeValueAsString(Object value)
to do whatever you want. Here is cool tutorial for ObjectMapper
and Here are the Maven dependencies you might need to use it:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
Here is javadoc for ObjectMapper
Upvotes: 0
Reputation: 128
Using JSON Library
JSONArray arr = new JSONArray();
JSONObject obj = new JSONObject();
obj.put("temperature", "-12");
obj.put("sendtimes", "1000");
arr.put(obj);
obj = new JSONObject();
obj.put("pressure", "1000");
obj.put("sendtimes", "1001");
arr.put(obj);
JSONObject finalObj = new JSONObject();
finalObj.put("temperaturData", arr);
System.out.println(finalObj);
Though what I suggest is that, you should better assign keys to the given inner arrays too, which will make accessing it easy and bug free.
Upvotes: 1
Reputation: 342
It is quite simple what you want to achieve. I am using JavaScript, same can be achieved with any other language using similar data structure. What you want to do is create an array and append the values to that array.
var tempData = {"temperaturData" : []}
tempData["temperaturData"].push({"temperature": -12, "sendtimes": 10000})
tempData["temperaturData"].push({"pressure" : 1000, "sendtimes" : 10001})
tempData["temperaturData"].push({"altitude" : 100.7, "sendtimes" : 10002})
JSON.stringify(tempData)
Upvotes: 0