*I am already getting this JSON object from responce.body(). I want every data inside this separately in variable. I am using java.
{
"Classes":{
"Primary":{
"Classes":{
"1":{
"section":[
"a",
"b"
]
},
"2":{
"sections":[
"a",
"b"
]
}
}
}
}
}
*I know how to get the JSONObject but i dont know how can i get that array inside "section". even if i get that array with JSONArray then how to convert it to JSONObject? or String.
*Note that inside value of "section" array is dynamic, value inside that array is dynamic and can be multiiple from "a" to "z". Also JSONObject inside "Classes"(inside primary) is also dynamic. there can be dynamic and multiple "1","2"... and it is string, It is not necessary that there will be incremental numbers.
After 30 mins of war, I find out your answer just copy this code and paste where you want to use -
Here it is -
String json = "{
"Classes": {
"Primary": {
"Classes": {
"1": {
"section": [
"a",
"b"
]
},
"2": {
"sections": [
"a",
"b"
]
}
}
}
}
}";
try {
JSONObject jsonObject = new JSONObject(json);
Log.d("jsonObj", jsonObject.toString());
JSONObject classJsonObj = jsonObject.optJSONObject("Classes");
JSONObject primaryJsonObj = classJsonObj.optJSONObject("Primary");
JSONObject internalClassJsonObj = primaryJsonObj.optJSONObject("Classes");
if(internalClassJsonObj != null){
int i = 1;
JSONObject dynmaicInternalJsonObj = null;
while (true){
dynmaicInternalJsonObj = internalClassJsonObj.optJSONObject(i+"");
if(dynmaicInternalJsonObj != null){
JSONArray sectionJsonArr = dynmaicInternalJsonObj.optJSONArray("sections");
Log.d("SectionArr", sectionJsonArr.toString());
// Finally you got your section data here...
if(sectionJsonArr != null){
for(int j=0; j<sectionJsonArr.length(); j++){
System.out.println("Dynamic Sections Data is: - " + sectionJsonArr.opt(j));
}
System.out.println("\n\n");
}
}else{
break;
}
i++;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
You've tagged this as java so I can only assume you want a solution for that language.
To use this data it needs to parsed, this means you are converting the data into a more usable type.
Click this to learn how to parse JSON in java
Assuming you need solution in java, use this to get a object classes for your json structure and then convert your json to java objects using libraries like GSON.
Example:
String json = "{\"city\":\"San Jose\", \"state\": \"CA\", \"country\":\"USA\"}";
Gson gson = new Gson();
Place place = gson.fromJson(json, Place.class);
If you are using ionic (typescript or javascript), you can use the below approach
var json = "{
"Classes": {
"Primary": {
"Classes": {
"1": {
"section": [
"a",
"b"
]
},
"2": {
"sections": [
"a",
"b"
]
}
}
}
}
}";
for(let item in json.Classes.Primary.Classes){
console.log(item.sections);
}
If you want to display the same data in frontend using html, use *ngFor
<div *ngFor="let item in json.Classes.Primary.Classes ">
<h5>{{item.sections}}</h5>
</div>
I hope it helps.
Related
This is my json from the code below:
"ict":[
{
"module1":{
"1":[
"OS",
"Operating system"
],
"2":[
"CA",
"Computer Application"
],
"3":[
"CM",
"Computational Mathematics"
],
"4":[
"CA",
"Computer Application"
],
"5":[
"Programming",
"Structured Programming"
]
},
I want to access this part
"1":["OS","Operating system"]
but get the string "OS" without fetching the whole string.
When I run my java code which is this:
private void addItemsFromJSON() {
try {
JSONObject jsonObject = new JSONObject(readJSONDataFromFile());
JSONArray coursea = jsonObject.getJSONArray("ict");
for (int i = 0; i < coursea.length(); i++) {
JSONObject cc = coursea.getJSONObject(i);
JSONObject contact = cc.getJSONObject("module1");
courses.add(new course(contact.getString("1"),"",String.valueOf(content.get(ran.nextInt(content.size())))));
}
} catch (JSONException | IOException e) {
Log.d(TAG, "addItemsFromJSON: 777", e);
}
}
The output that I get is ["OS", "Operating system"]
How can I retrieve only the first object from a json key array with multiple values?
The data at "1" refers to another JSONArray, so to get the first item in the array you would do something like this:
JSONArray array = contact.getJSONArray("1");
array.getString(0);
In JSON objects are denoted using {} and arrays with []. If you're trying to access a specific value in your JSON object then it's really just a case of following the path to it, through the arrays and objects.
So, I tried something with java which looks like this, but the output does not look nice.
One of the code-examples I tried to make a json file with:
String name = "usericals.json";
JSONObject jsonObj = new JSONObject();
JSONArray scene = new JSONArray();
JSONArray element = new JSONArray();
jsonObj.put("scene", scene);
for (int i = 0; i < 1; i++) {
for (int ii = 0; ii < 1; ii++) {
element.put(write);
}
jsonObj.put("element", element);
}
scene.put(element);
try (PrintWriter writer = new PrintWriter("new.json", "UTF-8")) {
writer.write(jsonObj.toString(4));
} catch (Exception ex) {
System.out.println("exception " + ex);
}
I wanted to make a json file which looks like this but I cannot get it right. I am creating with my code above only arrays. Does anyone have an idea or suggestion?
The JSON File I want:
{
"scene": [
{
"id": 0,
"calendar_event": "urlaub",
"element": [
{
"anything": ""
},
{
"anything": ""
}
]
},
{
"id": 1,
"calendar_event": "urlauburlaub",
"element": [
{
"anything": ""
},
{
"anything": ""
}
]
},
{
"id": 2,
"calendar_event": "urlauburlauburlaub",
"element": [
{
"anything": ""
},
{
"device": "",
"anything": ""
}
]
},
{
"id": 3,
"calendar_event": "urlauburlauburlauburlaub",
"element": [
{
"anything": ""
},
{
"anything": ""
}
]
}
]
}
I suggest using library for that. Jackson or GSON would be a good choice.
Instead of manually creating json field by field you could create POJOs and then use Jackson's ObjectMapper. Example:
public class Car {
private String color;
private String type;
// standard getters setters
}
and then
ObjectMapper objectMapper = new ObjectMapper();
Car car = new Car("yellow", "renault");
objectMapper.writeValue(new File("target/car.json"), car);
Which will give
{"color":"yellow","type":"renault"}
Google has a lot of jackson tutorials!
Use JSONObject recursively. Try something like this (I add some extra indentation so it can be readed easily, but on real projects better use functions instead):
JSONObject json = new JSONObject();
JSONArray scene = new JSONArray();
JSONObject node = new JSONObject();
node.put("id", 0);
node.put("calendar_event", "urlaub");
JSONArray element = new JSONArray();
JSONObject enode = new JSONObject();
enode.put("anything", "");
element.add(enode);
//...
node.put("element", element);
scene.add(node);
json.put("scene", scene);
//...
Note like this you generate manually the JSONs, but there are other libraries that scan objects to generate jsons. Depending on your needs, it could be easer, but remember that making so you are going to overhead everything because you are going to need to hold in memory two copies of the same tree. Also dealing with hierarchical structures maybe a problem using plain java objects.
I am building a tool using java, that accesses an API.
I'm trying to let the user decide, which parameters to use (via checkboxes for instance).
So the user would decide to take one of let's say 5 parameters:
p1
p2
p3
p4
p5
and then I would make a call to the API using those parameters and receive a Json String as a response.
So that Json String can be either
{"data":[{"p1":"value1", "p2":"value2", "p3":"value3", "p4":"value4", "p5":"value5"}]}
{"data":[{"p1":"value1", "p2":"value2", "p3":"value3", "p4":"value4"}]}
{"data":[{"p1":"value1", "p2":"value2", "p3":"value3"}]}
{"data":[{"p1":"value1", "p2":"value2"}]}
or
{"data":[{"p1":"value1"}]}
I'm trying to print everything inside "data" to the console. This is the code I got so far:
JsonParser parser = new JsonParser();
JsonObject json = (JsonObject)
parser.parse(adsInsights.toString());
System.out.println(json.get("p1").getAsString() + "\t"
+ json.get("p2").getAsString() + "\t"
+ json.get("p3").getAsString() + "\t"
+ json.get("p4").getAsString() + "\t" +
json.get("p5").getAsString()
);
My problem is: how do I determine which ones to print, without doing a ton of if/elses?
All I need is every variable within "data". is there a method to do this?
EDIT:
First of all, thanks for all the answers.
For future reference I guess, this is what I did:
//getting the keys, which the user has selected. Detailed implementation irrelevant for this matter
String selectedKeys[] = getSelectedKeys();
JsonParser parser = new JsonParser();
JsonObject json = (JsonObject)
parser.parse(adsInsights.toString());
for(int i = 0; i < selectedKeys.length; i++) {
if(json.has(selectedKeys[i])) {
System.out.print(json.get(selectedKeys[i]).getAsString() + "\t");
}
}
System.out.println();
You can iterate over the Json keys no matter which keys are in it and print their values.
JsonParser parser = new JsonParser();
JsonObject json = (JsonObject)
parser.parse(adsInsights.toString());
for (key: json.keys) {
System.out.print(json.get(key).getAsString());
}
// to check if key exists or not. if not, return empty string.
private String getValues(JSONObject jsonObj, String arg) {
return jsonObj.get(arg) != null?(String) jsonObj.get(arg):"";
}
//call getValues function for every key. fetch all keys from keySet Function.
JSONObject check=(JSONObject) obj;
JSONObject data=(JSONObject) check.get("data");
Set<String> keys=data.keySet();
for(String k:keys){
System.out.println(getValues(data,k));
}
Are you building the API as well?
I think a better data structure to return from the API would be to use an array for "data", e.g.
{
"data":[
{ "id": "p1", "value": "value1" },
{ "id": "p2", "value": "value2" },
{ "id": "p3", "value": "value3" },
{ "id": "p4", "value": "value4" },
{ "id": "p5", "value": "value5" }
]
}
That way, the receiving code doesn't have to care about which items are in data, or how many. Instead it can just loop through the array and print whatever happens to be there.
I have json file in below format.
{
"data":[
{
"prjId": 1,
"name" : "Forj1",
"issue": [
{
"id": 00001,
"status" : "Closed"
},
{
"id": 00002,
"status" : "Open"
}
]
},
{
"prjId": 2,
"name" : "Forj2",
"issue": [
{
"id": 00003,
"status" : "Closed"
},
{
"id": 00004,
"status" : "Open"
}
]
}],
"issueCounter": 7,
"success": true
}
Here "data" is array of projects, and within project attribute there is array of "issue".
So far if I remove "issue" array, I am able to traverse the json to one level down in "data" attribute, If this json has "issue" array I get an error saying missing comma.
javax.json.stream.JsonParsingException: Invalid token=NUMBER at (line no=15, column no=14, offset=242) Expected tokens are: [COMMA]
Below is the code that I have right now. I have two problems with this, one is the error while reading if I place the "issue" attribute, and secondly a way to read the "issue" array and traverse all attributes within.
InputStream fis = new FileInputStream(pathToFile+"data3.json");
JsonReader jsonReader = Json.createReader(fis);
//the error is thrown on below line while reading the above json.
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();
fis.close();
System.out.println(jsonObject.getInt("issueCounter"));
//reading arrays from json
JsonArray jsonArrayData = jsonObject.getJsonArray("data");
Project [] prj = new Project[jsonArrayData.size()];
int index = 0;
for(JsonValue value : jsonArrayData){
JSONObject jsonObj = new JSONObject(value.toString());
System.out.println(jsonObj.getString("name"));
System.out.println(jsonObj.getInt("prjId"));
//this is also the place where I am stuck, I know I need to construct an array out of it by obtaining issue attribute. Below is very very wrong.
/*
JsonArray jsonArrayIssue = jsonObj.getJsonArray("issue");
for(JsonValue issue : jsonArrayIssue){
JSONObject jsonIssueObj = new JSONObject(issue.toString());
System.out.println(jsonIssueObj.getString("status"));
System.out.println(jsonIssueObj.getInt("id"));
}
*/
}
Any help or pointers is deeply appreciated. I can tweak the json if its required ultimately I need to maintain an array of issues.
The problem as others said is the JSON.
"id": 00001 <-- this is a number, numbers cannot start with a leading zero as per JSON stadard.
If you control the JSON you should tweak it.
Alternatively ff you don't, you can use a less strict parser like org.json.simple https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
The code will be the same as yours, just adjusted to org.json.simple
try { ...
JSONObject rootJSON = (JSONObject) new JSONParser().parse(jsonString);
JSONArray dataList = (JSONArray) rootJSON.get("data");
for(Object projectObj: dataList.toArray()){
JSONObject project = (JSONObject)projectObj;
JSONArray issueList = (JSONArray) project.get("issue");
for(Object issueObj: issueList.toArray()){
JSONObject issue = (JSONObject) issueObj;
//do something with the issue
}
}
} catch (ParseException e) {
//do smth
e.printStackTrace();
}
Your json data is invalid.You can check here.
http://jsonlint.com
...issue": [{ "id": 00001,
"status": ----------------------^
Your id must be string number,string,boolean.Send 1,2,3,.... as return values and check if it works.
Your code looks okay the problem is the JSON formatting. Specifically the following lines:
"id": 00001,
"id": 00002,
"id": 00003,
"id": 00004,
Basically if you want it in that format you will need to set them as strings by wrapping the values in quotations i.e. "id": "00001" or you can use a valid number i.e. "id": 1
so, there's this JSON code. Im trying to get the "abridged_cast".
but its complicated.
its JSONObject
inside JSONArray onside jSONObject Inside JsonArray....
{
"total": 591,
"movies": [
{
"title": "Jack and Jill",
"year": 2011,
"runtime": "",
"release_dates": {
"theater": "2011-11-11"
},
"ratings": {
"critics_score": -1,
"audience_score": 90
},
"synopsis": "",
"posters": {
"thumbnail": "",
"profile": "",
"detailed": "",
"original": ""
},
"abridged_cast": [
{
"name": "Al Pacino",
"characters": []
},
{
"name": "Adam Sandler",
"characters": []
},
{
"name": "Katie Holmes",
"characters": []
}
],
"links": {
"self": "",
"alternate": ""
}
}
],
"links": {
"self": "",
"next": ""
},
"link_template": ""
}
this is my code for getting "title" and "year"
if (response != null) {
try {
// convert the String response to a JSON object,
// because JSON is the response format Rotten Tomatoes uses
JSONObject jsonResponse = new JSONObject(response);
// fetch the array of movies in the response
JSONArray movies = jsonResponse.getJSONArray("movies");
// add each movie's title to an array
movieTitles = new String[movies.length()];
for (int i = 0; i < movies.length(); i++) {
JSONObject movie = movies.getJSONObject(i);
movieTitles[i] = movie.getString("title");
}
hope someone would help me because i cant figure out how to get the abridged_cast"
movies contains an array of "movie" objects. Each one of those objects contains a field abridged_cast that is an array of (let's call them "cast member") objects.
If you're not going to map to a POJO and instead are going through the JSON, you simply need to get that array in your loop after getting movie, and get each "cast member" object from that array in the same manner using another loop.
...
JSONArray cast = movie.getJSONArray("abridged_cast");
for (int j = 0; j < cast.length(); j++) {
JSONObject castMember = cast.getJSONObject(j);
...
}
Edit from comments: Your original question involved how to extract the information from the JSON you have; the above code explains that. It now seems like you're asking a more fundamental programming question around how to use it.
If you're going to use the included org.json classes that come with Android, you now know how to access the information in the returned JSON object. And you could write methods around the parsed JSONObject to access the data as-is using the objects and methods from the json.org package. For example, you could write a "getMovie()" method that took the name of the movie as a string and searched that "movies" array for the right one and returned it as a JSONObject.
Normally you would create classes in Java that encapsulate the data returned in that JSON and use data structures that lend themselves to your access patterns (For example, a Map that conatained all the movies using their names as keys). Using the org.json classes you'll have to instantiate those objects and populate them manually as you parse the JSON like you're doing in your question. If you used either the Gson or Jackson JSON parsing libraries they are capable of taking the JSON you have and mapping all the data to the classes your create and returning them in a single call.
try {
String Movie = null;
String abridged = null;
JSONArray jsonResponse = new JSONArray(response);
for (int i = 0; i< jsonResponse.length(); i++) {
Movie = jsonResponse.getJSONObject(i).getString("movies").toString();
System.out.println("movies="+Movie);
abridged = jsonResponse.getJSONObject(i).getString("abridged_cast").toString();
}
JSONArray jArray = new JSONArray(Movie);
for (int i = 0; i< jArray.length(); i++) {
String title = jArray.getJSONObject(i).getString("title").toString();
System.out.println("title="+title);
}
JSONArray jabridgeArray = new JSONArray(abridged);
for (int i = 0; i< jabridgeArray.length(); i++) {
String title = jabridgeArray.getJSONObject(i).getString("name").toString();
System.out.println("title="+title);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}