{
"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));
Related
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"}
I have a json (result) like the below , i need the value of Key "extra", that is "contact office".
I tried the below code, but it did not work, can you help?
JSONArray jsonArray = new JSONArray(result.toString().trim());
JSONObject json = jsonArray.getJSONObject(0).getJSONObject("student").getJSONArray("department").getJSONObject(0).getJSONObject("classes");
String val=json.getString("extra");
// JSON Example
{
"student": [
{
"department" : [
{
"classes" : [
{
"grade" : "A",
"fine" : "No"
},
{
"grade" : "B",
"fine" : "Yes",
"extra" : "contact office"
},
{
"grade" : "C",
"fine" : "NA"
}
],
}
],
}
],
}
You mixed up JSONArray and JSONObject a few times, not sure exactly what I had to change but the following will work:
JSONObject jsonObject = new JSONObject(result.toString().trim());
JSONArray jsonArray = jsonObject
.getJSONArray("student").getJSONObject(0).getJSONArray("department").getJSONObject(0)
.getJSONArray("classes");
String val = jsonArray.getJSONObject(1).getString("extra");
Is this a full sample? If so it doesn't start out as an array. Student is and object not an array. If it is just a sample of one item in the array then you're okay.
The second thing I noticed is: getJSONObject("classes"). Classes is an array not an object, this won't work.
Would you like to consider using JsonPath. You could do something like this -
String[] extraValues = JsonPath.read(json, "$.student[0].department[0].classes[*].extra");
I have this below json content in a file.
[
{
"prjId": 1,
"name" : "ABC",
"issueCounter": 7,
"issue": [
{
"id": 1,
"status" : "Closed",
"comment" : "blah blah blah",
"loggedBy": "shdkjdlsj"
},
{
"id": 2,
"status" : "Open",
"comment": "nothing",
"loggedBy": "xyz"
}
]
},
{
"prjId": 2,
"name" : "XYZ",
"issueCounter": 7,
"issue": [
{
"id": 3,
"status" : "Closed",
"comment": "jjjjjjjj",
"loggedBy": "klwm"
},
{
"id": 4,
"status" : "Closed",
"comment": "test test test",
"loggedBy": "NACK"
}
]
}]
I am able to parse this file and then traverse this json to get to the node where i wish to update. Upon reaching that point, i am confused on how to update it so that it would reflect on file on filesystem.
JSONParser parser = new JSONParser();
JSONArray rootArray = (JSONArray) parser.parse(new FileReader(pathToFile+fileName));
JSONObject project=null;
for (Object rootEntry : rootArray)
{
project = (JSONObject) rootEntry;
if( 1 == (Long) project.get("prjId"))
{
JSONArray issueArray = (JSONArray) project.get("issue");
for (Object issueEntry : issueArray)
{
JSONObject issue = (JSONObject) issueEntry;
System.out.println((Long) issue.get("id"));
if(2==(Long) issue.get("id"))
{
//now update the "comment" attribute here.
System.out.println("updated the comment: "+trckParam.getComment());
}
}
}
I have just the json reader till this point so do I construct a String as-and-when I traverse the nodes and when i reach the point I need to update, I update it (and construct the remainder of the nodes in this json object, (not to break from the loop)) and then write the entire reconstructed string to same file? Or is there a better approach where I can traverse the JSONObject and once i update it, push the entire object onto a file without constructing a String of entire file.
I still need to figure out a way to take either of the approach. So any pointers or direction will be greatly helpful.
How to convert following type Json array in "tags_name": ["Activity Based"] in android and store data using getter setter methods.How to create POJO class, and how to handle when array is empty.I am struck with this concept.I tried this following way. Please guide me to resolve this issue.
API
"postlist": [
{
"posts": {
"pm_post_id": "4647",
},
"tags_name": [
"Activity Based"
],
"images_count": 0,
"images": [],
"post_user": [
{
"first_name": "Michelle",
"last_name": "Smith",
"profile_pic": "profess_sw_engg.jpg"
}
],
"is_encourage_user": true,
"encourage_feed_id": "992"
},
{
"posts": {
"pm_post_id": "4647",
},
"tags_name": [],
"images_count": 2,
"images": [
{
"gallery_id": "5549",
"name": "IMG_20161012_1832491.jpg",
},
{
"gallery_id": "5550",
"name": "IMG_20161012_1832441.jpg",
}
],
"post_user": [
{
"first_name": "Michelle",
"last_name": "Smith",
"profile_pic": "profess_sw_engg.jpg"
}
],
"is_encourage_user": true,
"encourage_feed_id": "993"
}
]
In Java i've use Following code.
try {
JSONArray tagNameArr = tempPostObject.getJSONArray("tags_name");
for(int iloop=0;i<tagNameArr.length();iloop++)
{
String street = tagNameArr.getString(iloop);
Log.i("..........",""+street);
}
} catch (Exception e) {
e.printStackTrace();
}
try this to get value of tags_name JSONArray.
ArrayList<String> temp = new ArrayList<String>();
JSONArray tagName= jsonResponse.getJSONArray("tags_name");
for(int j=0;j<tagName.length();j++){
temp.add(tagName.getString(j));
}
Use jsonschema2pojo.org service and Gson converter (lib from Google). select Gson converter on the site.
You can use gson
Gson gson = new GsonBuilder().serializeNulls().create();
RestaurantLoginResponseClass restaurantLoginResponse = gson.fromJson(loginResponseJsonString, RestaurantLoginResponseClass.class);
Add dependencies in app.gradle
compile 'com.google.code.gson:gson:2.6.2'
#MohanRaj , why you would to parse it ! , it is not clear , if you would to get the values and retain it in java object or save it in file system , you can use :
Gs
Gson gson = new Gson();
Staff obj = gson.fromJson(jsonInString, Staff.class);
if you have a list of object inside your json
you can create a list in your staff class something like :
#SerializedName("hits")
private List<Car> cars = new ArrayList<Car>();
GSON can understood it and parse the incoming list to those object .
you can get POJO from familiar JSON to java POJO tools :
http://www.jsonschema2pojo.org/
and you can check for more info https://sites.google.com/site/gson/gson-user-guide
http://www.java2blog.com/2013/11/gson-example-read-and-write-json.html
I'm currently implementing JSON parsing in my game but I've encountered a problem that I can't find a solution for: how do you parse a specific node/object (not sure what to call it) from a JSON file? Let's say my JSON looks like this:
{
"intro/credits": { //A node/object.
"title": "Intro music / Credits music",
"authors": [
{
"name": "Vindsvept",
"links": {
"YouTube": "https://www.youtube.com/channel/UCfSUheoljDlGDjerRylO4Nw",
"Bandcamp": "https://vindsvept.bandcamp.com/"
}
}
]
},
"extra": { //Another node/object.
"title": "extra",
"authors": [
{
"name": "extra",
"links": {
"linkTest": "linkTest"
}
}
]
}
}
With that JSON in mind, how would I do something like this?:
MyObject myObj = json.fromJson(parse.object.called.extra);
Thanks to Underbalanced I can now answer my own question: to exctract an object called extra you would do something like this:
Json json = new Json();
JsonValue root = new JsonReader().parse(Gdx.files.internal("path/to/your/file.json"));
JsonValue extra = root.get("extra"); //Replace 'extra' with whatever your object is called.
MyObject myObj = json.fromJson(MyObject.class, extra.toString());