I am learning to work with json files and I'm using the JSON-java library from https://github.com/stleary/JSON-java
I was able to manipulate data for this json dataset
{
"timezone": "UTC",
"serverTime": 1602321831628,
"rateLimits": [
{
"rateLimitType": "REQUEST_WEIGHT",
"interval": "MINUTE",
"intervalNum": 1,
"limit": 1200
}
],
"symbols": [
{
"symbol": "ETHBTC",
"status": "TRADING"
}
]
}
Using this code
JSONTokener jsonToken = new JSONTokener(new FileReader(fileName));
JSONObject jsonObject = new JSONObject(jsonToken);
//extract all base asset array
JSONArray symbols = jsonObject.getJSONArray("symbols");
Now I want to manipulate a dataset like this from a .json file
[
{
"symbol": "ETHBTC",
"priceChange": "-0.00029700"
},
{
"symbol": "LTCBTC",
"priceChange": "-0.00003300"
}
]
How do I import this data into my program as an array? I have looked for 8 hours, but could not find a solution. Thank you.
You are almost there, all you have to do is to new a JSON array from jsonToken as follows:
BTW, I think the JSON library you are using is org.json, not JSON.ORG. And both of your JSON strings are invalid, if no other JSON object exists behind comma, please remove it.
Code snippet
JSONTokener jsonToken = new JSONTokener(new FileReader(fileName));
JSONArray jsonArray = new JSONArray(jsonToken);
System.out.println(jsonArray.toString());
System.out.println(jsonArray.get(0));
Console output
[{"priceChange":"-0.00029700","symbol":"ETHBTC"},{"priceChange":"-0.00003300","symbol":"LTCBTC"}]
{"priceChange":"-0.00029700","symbol":"ETHBTC"}
Related
I need to read the output of a BufferedReader object which is in json format, parse the json and extract some values. My code looks as below:
BufferedReader reader = new BufferedReader(new
InputStreamReader(proc1.getInputStream()));
Stream<String> s = reader.lines();
Object[] t = s.toArray();
String result = Arrays.toString(t);
JSONParser jp = new JSONParser();
JSONArray jArr = (JSONArray) jp.parse(result);
System.out.println(jArr);
The JSONArray jArr looks as below:
[
{
"result": {
"totalSize": 1,
"records": [
{
"Owner_Name": "User Group",
"Creation_Date": "2020-12-15",
"attributes": {
"type": "Case",
"url": "http://google.com"
},
"Version_Number": 0
}
],
"done": true
},
"status": 0
}
]
I need to get the properties of "records". I have the subsequent code working, just need to create a json object with the values inside "records". Output json object required is:
{"records": [
{
"Owner_Name": "User Group",
"Creation_Date": "2020-12-15",
"attributes": {
"type": "Case",
"url": "http://google.com"
},
"Version_Number": 0
}
I am facing json array and json object incompatibility issues while trying to case jArr as json object. Can someone suggest a way to do this
Join the stream as a single String. Use try-with-resources so the BufferedReader gets closed.
String result;
try (Stream<String> stream = reader.lines()) {
result = stream.collect(Collectors.joining());
}
I would like to be able to parse a JSON file that is structured something like:
[
{
"id": 1,
"name": {
"first": "name",
"secound": "name",
"last": "name"
},
"skills": [
"python",
"javascript"
],
"otherInfo": {
"something": 45,
"something2": 49
}
},
{
"id": 2,
"name": {
"first": "name",
"secound": "name",
"last": "name"
},
"skills": [
"python",
"javascript"
],
"otherInfo": {
"something": 45,
"something2": 49
}
}
etc...
]
into something looking like
array(
[0] => array(
0 => "id"
1 => "firstname"
2 => "otherData"
),
[1] => array(
0 => "id"
1 => "firstname"
2 => "otherData"
),
etc...
)
I'm pretty sure i have an idea on how to convert it into the format I want, but im having trouble actually reading the data from the file.
The two major issues im having:
Reading it from inside the jar.
Most of the examples used json.simple, and the json library i'm using doesn't seem to have that.
I tried some examples online, and a couple of the answers on this post
but no luck the biggest issue is that all of them are giving examples for reading an external file, while I'm trying to read one that is packaged inside the jar.
My project tree:
MyProject
L src
L myPackage
L MyClass.java
L MyJsonFile.json
The closest thing that I'm guessing almost worked is this (from the link above):
import org.json.JSONArray;
//code
JSONArray myJSONArray = new JSONArray(Main.class.getResourceAsStream("myFile.json"));
But that only seems to throw an error:
org.json.JSONException: JSONArray initial value should be a string or collection or array.
Thanks in advance!
The problem is org.json.JSONArray will only accept String,Collection or Array but you are trying to pass the InputStream object. which is what error messages also says
org.json.JSONException: JSONArray initial value should be a string or collection or array
So first convert the InputStream into String
InputStream inputStream = Main.class.getResourceAsStream("myFile.json");
InputStreamReader isReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(isReader);
StringBuffer sb = new StringBuffer();
String str;
while((str = reader.readLine())!= null){
sb.append(str);
}
And then convert it into JSONArray
JSONArray myJSONArray = new JSONArray(sb.toString());
After here you can iterate the JSONArray using for loop, like here
How do you parse a nested JSON file like below using Processing JSON object? I am trying to figure out how to parse JSON that is multi-level.
{
"info": {
"description": "COCO 2014 Dataset",
"url": "http://cocodataset.org",
"version": "1.0",
"year": 2014,
"contributor": "COCO Consortium",
"date_created": "2017/09/01"
},
"images": [
{
"license": 5,
"file_name": "COCO_train2014_000000057870.jpg",
"coco_url": "http://images.cocodataset.org/train2014/COCO_train2014_000000057870.jpg",
"height": 480,
"width": 640,
"date_captured": "2013-11-14 16:28:13",
"flickr_url": "http://farm4.staticflickr.com/3153/2970773875_164f0c0b83_z.jpg",
"id": 57870
},
Have a look at JSONObject and JSONArray to see the available methods bellow on each page, each with documentation and examples.
Regarding your structure, here's a quick snippet on how you might access nested JSON objects and arrays:
// assume data is a JSONObject pointing to the loaded json data (via loadJSONObject / JSONObject.parse(), etc.
// access the info object
JSONObject info = data.getJSONObject("info");
// access the images array object
JSONArray images = data.getJSONArray("images");
// access a string inside an object
println(info.getString("description"));
// access a JSON object inside a JSON array
JSONObject firstImage = images.getJSONObject(0);
// acess an integer
println(firstImage.getInt("id"));
// ... and a string again
println(firstImage.getString("flickr_url"));
If you name your loaded JSONObject variable data, paste the the snippet above and run, it should print:
COCO 2014 Dataset
57870
http://farm4.staticflickr.com/3153/2970773875_164f0c0b83_z.jpg
You can use Gson to parse/deserialize to model class.
Or if you want to parse manually, then you have to parse a json object first and then you have to parse it again from a parsed json.
Eg.
JsonObject jsonObject = new JsonObject(jsonString);
JsonObject infoObject = jsonObject.getJsonObject("info");
String description = infoObject.getString("description");
{
"vers": 0.01,
"config": {
"rate": "perhr",
"valueColumns": [
"vCPU",
"ECU",
"memoryGiB",
"storageGB",
"linux"
],
"currencies": [
"USD"
],
"regions": [
{
"region": "us-east",
"instanceTypes": [
{
"type": "generalCurrentGen",
"sizes": [
{
"size": "t2.micro",
"vCPU": "1",
"ECU": "variable",
"memoryGiB": "1",
"storageGB": "ebsonly",
"valueColumns": [
{
"name": "linux",
"prices": {
"USD": "0.013"
}
}
]
},
{
"size": "t2.small",
"vCPU": "1",
"ECU": "variable",
"memoryGiB": "2",
"storageGB": "ebsonly",
"valueColumns": [
{
"name": "linux",
"prices": {
"USD": "0.026"
}
}
]
}
]
}
]
}
]
}
}
Hi, i wanted to read this json file. I tried various ways from google but getting a null at valuesColumns. I have to read sizes array and have to put in list.
I think it will help your cause if you format your json. As it is it's quite hard to read. Googling for a JSON beautifier quickly found me this one.
When working with JSON your browser console provides a nice environment for inspecting and playing with the data. I pasted it into the browser console and did (hit enter after each line):
var x = { ... paste JSON here ... }
x
x.config
x.config.valueColumns
This tells me that x is a JSON object, config is a JSON object and valueColumns is a JSON array
Now to java. Grab yourself a json library, and accessing valueColumns will be something like:
JSONObject x = new JSONObject("{ ... JSON string ... }");
JSONObject config = x.getJSONObject("config");
JSONArray valueColumns = config.getJSONArray("valueColumns");
You can then iterate over valueColumns and pull out what you need.
Note that the above only gets you to the first valueColumns array under config. By following the same principle you can go deeper into the structure and get out the valueColumns for the objects in the sizes array if that's what you're really after.
For parsing json to java there are simple step.
Below code snippet may help you.
// parse json to java
Object obj = parser.parse(s);
JSONObject json = (JSONObject) obj;
JSONObject o = (JSONObject) json.get("config");
//get json array.
JSONArray array = (JSONArray) o.get("valueColumns");
System.out.println(array.toJSONString());
//access element by index
System.out.println(array.get(0));
My doubt is if there is any tool on-line or not to generate a string from a JSON. For example, I have this JSON:
{
"my_json": [
{
"number": 20,
"name": "androider",
},
{
"id": 3432,
"name": "other_name",
}
]
}
If I want to declare a String in my code with this values, so I have to write many quotation marks to have my JSON in a String acceptable format.
So I want to know if thre is some tool to generate this String?
Some good choices are:
Jackson
Gson
They have built in methods to do just whatever you need to do in an efficient way...
I can't quite tell what you want from your original question, but I assume you are trying to output a Java String that contains some JSON that you have generated.
You should use JSONObject and JSONArray to accomplish this.
To create this JSON:
{
"my_json": [
{
"number": 20,
"name": "androider",
},
{
"id": 3432,
"name": "other_name",
}
]
}
You should use this code:
JSONObject a = new JSONObject();
a.put("number", 20);
a.put("name", "androider");
JSONObject b = new JSONObject();
b.put("id", 3432);
b.put("name", "other_name");
JSONArray array = new JSONArray();
array.put(a);
array.put(b);
JSONObject root = new JSONObject();
root.put("my_json", array);
// convert the root object to a string with 4 spaces of indentation
String json = root.toString(4);
As told by Angel, Jackson and Gson are two cool libs.
Gson is very easy to use while Jackson has better performance.
Try here, Go through the answers mentioned below
How to convert String to JSONObject in Java
in short,
Using org.json library:
JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
Here put your own string.
Edit:
Try here,
http://www.mkyong.com/java/json-simple-example-read-and-write-json/
Create a Json object,
JSONObject jsonobj = new JSONObject();
Put your data using...
josnobj.put()