Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I have the following json:
{
"count" : "1567",
"program" : ["NDBC Meteorological\/Ocean", "International Partners"],
"owner" : ["NDBC", "Alaska Ocean Observing System"],
"station" : [{
"id" : "00922",
"lat" : "30",
"lon" : "-90",
"name" : "OTN201 - 4800922"
}
]
}
I need just to get station information like the id, lat, lon, name etc. But I cannot get it to work, here's my code:
//////response_str is the json string///////
JSONArray pages = new JSONArray(response_str);
for (int i = 0; i < pages.length(); ++i) {
JSONObject rec = pages.getJSONObject(i);
JSONObject jsonPage =rec.getJSONObject("station");
String name= jsonPage.getString("name");
System.out.println(name);
}
Any help will be greatly appreciated, Regards
station is JSONArray instead of JSONObject so you will need to first get JSONArray from main JSONObject then extract all id,lat,lon,.. from JSONObject. change your code as:
JSONArray pages = new JSONArray(response_str);
for (int i = 0; i < pages.length(); ++i) {
JSONObject rec = pages.getJSONObject(i);
JSONArray jsonPage =rec.getJSONArray("station");
// get JSONObject
JSONObject jsonstation =jsonPage.getJSONObject(0);
String name= jsonstation.getString("name");
System.out.println(name);
}
The root is a JSONObject not a JSONArray and it contains, three JSONArray named programm, station and owner and the count field. You should change your code accordingly with the JSON structure
You don't need the outside loop at all
JSONObject jMain = new JSONObject( response_str);
JSONArray jStationList =jMain.getJSONArray("station");
JSONObject jStation =jStationList.getJSONObject(0);
String name= jsonstation.getString("name");
..etc
You're issue is that you're referring to the source string as a JSONArray when it is instead a JSONObject (brackets on the outside would indicate that is an array). The following gets the name of the station.
JSONObject pages = new JSONObject(response_str);
for (int i = 0; i < pages.length(); ++i)
{
JSONArray stationInfo =rec.getJSONArray("station");
String name= stationInfo.getString("name");
System.out.println(name);
}
Related
I have a java project in which I take a JSON and read its contents. I'm using org.json libraries and I would like to iterate through JSONObjects which are nested in a JSONArray, which is nested in a JSONObject. I keep getting this error though: JSONArray initial value should be a string or collection or array. I'm specifically getting the JSON from a web source, but here is an example of one: http://jsonblob.com/1062033947625799680
I'm particularly concerned about the fact that each player profile is unnamed, but there may be a simple fix for that.
I'd like to get access to each player profile and here is what I have that is causing an error:
import org.json.*;
JSONObject JSON = new JSONObject(content1.toString());
JSONArray data = new JSONArray(JSON.getJSONArray("data"));
for(int z = 1; i<data.length(); i++)
{
JSONObject ply = new JSONObject(data.getJSONObject(z));
System.out.println(ply.toString());
}
I have a feeling I just don't fully understand the terminology of JSON and/or the library that I'm using, but any help is appreciated.
Try this instead:
JSONObject JSON = new JSONObject(content1.toString());
JSONArray data = new JSONArray(JSON.getJSONArray("data"));
for(int i = 0; i<data.length(); i++) {
JSONObject ply = data.getJSONObject(i);
System.out.println(ply.toString());
}
It turns out I just have to access the particular element in one line:
JSONObject JSON = new JSONObject(content1.toString());
JSONArray data = JSON.getJSONArray("data");
for(int z = 0; z<data.length(); z++)
{
//JSONObject ply = new JSONObject(data.getJSONObject(z));
String name = data.getJSONObject(z).getString("skaterFullName");
System.out.println(name);
}
This question already has answers here:
How to parse JSON array from file?
(3 answers)
Closed 5 years ago.
I´ve been trying to parse this Json format but since it has no name for the array i have no idea how to parse it... Thanks for your help and time.
Im using JSON simple library as a parser.
[
{
"Name":"John",
"LastName":"Wick"
},
{
"Name":"Johny",
"LastName":"Wicked"
}
]
the code im trying to use is this one :
JSONArray jsonarray = new JSONArray("data/names.json");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}
You can use Jackson built in tree model. For example like this
ObjectMapper mapper = new ObjectMapper();
JsonNode rootArray = mapper.readTree(new File("c:\\jsonfile.json"));
for(JsonNode root : rootArray) {
// your code
...
}
i'm creating a mcq for a medical application and i'm trying to get some question from my databse with the different choice with this JSON :
{
"QCM": [{
"question": "Est-ce que Guillaume a pris?",
"id": "34",
"choix": ["Oui", "Non"]
}]
}
then i past my question string to a textview and if i have 2 choice, i create only 2 button, but only 1 button is create and in my button i have this string :
["Oui", "Non"]
So i don't understand because i create a second JSONArray loop for it ...
Here is my Java
try
{
JSONArray QCM = response.getJSONArray("QCM");
for (int i=0; i<QCM.length(); i++) {
JSONObject getQcmObject = QCM.getJSONObject(i);
String questionGet = getQcmObject.getString("question");
symptomesQuestions.setText(questionGet);
for (int x=0; x<QCM.length(); x++){
JSONObject getChoixObject = QCM.getJSONObject(x);
String choiceGet = getChoixObject.getString("choix");
lesChoixButton.setText(choiceGet);
}
}
If someone can explain me how to do it, i want to learn ! can't find any exemple for this kind of request.
Thanks folks !
you use wrong parser ,change it like this:
JSONArray QCM = response.getJSONArray("QCM");
for (int i = 0; i < QCM.length(); i++) {
JSONObject getQcmObject = QCM.getJSONObject(i);
String questionGet = getQcmObject.getString("question");
symptomesQuestions.setText(questionGet);
JSONArray choiceGet = getChoixObject.getJSONArray("choix");
lesChoixButton1.setText(choiceGet.getString(0));
lesChoixButton2.setText(choiceGet.getString(1));
}
use this site to create java pojo model from your json : http://www.jsonschema2pojo.org/
I am a newbie to json parsing, I have grabbed a json string from a request and now I need to parse it with java. I'm using simple-lib for this. But I'm really stuck as I'm not familiar with it. I need to extract following data
I used following java code for that but it's not giving me the result I need, please someone help me...
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("test.json"));
JSONObject jsonObject = (JSONObject) obj;
JSONArray msg = (JSONArray) jsonObject.get("content");
Iterator<String> iterator = msg.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
Sample JSON
{
"status": 200,
"message": "ok",
"timestamp": "2014-05-22T14:29:56.824+03:00",
"pagesCount": 1,
"version": "1.1",
"pages": [
{
"number": 100,
"subpages": [
{
"number": 1,
"timestamp": "2014-05-22T13:41:41.116+03:00",
"content": "text"
},
Something like this perhaps?
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(new FileReader("test.json"));
JSONArray pages = (JSONArray) jsonObject.get("pages");
if (pages != null) {
for (Object p : pages) {
JSONObject page = (JSONObject) p;
JSONArray subPages = (JSONArray) page.get("subpages");
if (subPages != null) {
for (Object sp : subPages) {
JSONObject subPage = (JSONObject) sp;
System.err.println(subPage.get("content"));
}
}
}
}
You are requesting for the value that corresponds to the key content from your outermost object, but no such key exists in your sample input. In addition, the only field named content has a string as its value and not a JSON array.
To get at the content field you would need to walk the object hierarchy until you reach the element that you need, using something along these lines:
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(new FileReader("test.json"));
JSONArray pages = (JSONArray) json.get("pages");
// Page 10
JSONObject page = (JSONObject) pages.get(10);
// Subpages of page 10
JSONArray subpages = (JSONArray) page.get("subpages");
// Subpage 7 of page 10
JSONObject subpage = (JSONObject) subpages.get(10);
// Content of subpage 7 of page 10
String content = (String) subpage.get("content");
Please note that I am assuming that e.g. index 10 corresponds to page 10. That may not be true in your case; pages may not be zero-indexed, there may be missing pages or they may not be in the correct order. In that case you will have to iterate over the page and subpage lists and test the value of the number field to find the object that you need.
In any case, if you are indeed using json-simple, as seems to be the case, then JSONObject is a subclass of HashMap and JSONArray a subclass of ArrayList. Therefore, their interfaces should be quite familiar to you.
Disclaimer: Untested code - exception and other error handling removed for brevity
First of all, The json is not valid (if you pasted it complete)
In JSON "{}" is an object, and "[]" is an array, others are just key value pairs.
Simply you can do like this without using parser ,
JSONObject objResponseJSON = new JSONObject(responseJSONString);
int status = (int) objResponseJSON.getInt("status");
//fetch other
JSONArray pages = objResponseJSON.getJSONArray("pages");
for(int count = 0; count < pages.length(); count++){
//fetch other
JSONObject objJSON = pages.getJSONObject(count);
JSONArray subpages = objJSON.getJSONArray("subpages");
for(int count1 = 0; count1 < subpages.length(); count1++){
JSONObject objSubpageJSON = subpages.getJSONObject(count1);
//fetch other
int number = (int) objSubpageJSON.getInt("number");
}
}
I am using the package org.json package: I need help with getting the corect data from the json in java. this is the string I have in json:
{"GetLocationsResult":[{"ID":82,"Name":"Malmo","isCity":true,"isCounty":false,"isDisctrict":false,"ID_Parent":null,"ID_Map":35,"ZipCode":"7000"},{"ID":82,"Name":"Trelleborg","isCity":true,"isCounty":false,"isDisctrict":false,"ID_Parent":null,"ID_Map":35,"ZipCode":"7000"}]}
This is a listing and this is just a test, it will contain more than 2 items, so my questions is, I want to get the name of all locations, I want to populate a spinner with names in my android app.
How can I get the "Name":"Malmo" and so on....
???
The answer is simple....The JSON element starts with a { which is a JSON Object, and GetLocationsResults is a JSON Array of JSON Objects. In essence, I translated the JSON String to the following code...
JSONObject rootJson = new JSONObject(jsonString);
JSONArray jsonArray = rootJson.getJSONArray("GetLocationsResult");
//Let's assume we need names....
String[] names = null;
if (jsonArray != null) {
names = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
names[i] = json.getString("Name");
}
}
//Test
for (String name: names) {
System.out.println(name);
}