I can't loop through JSON Array for next Array - java

I try to learn Loop through a JSON object in Java for loop this case.But My json loop first array(ident AFL274) and stop not loop next array(CQH8971)(in json data have 2 arrays)I call this function by button.
this for call for json
public String getInfo(String url) {
try {
String result = HttpGet(url);
JSONObject json = new JSONObject(result);
JSONObject val = json.getJSONObject("SearchResult");
JSONArray data = val.getJSONArray("aircraft");
for(int i=0;i<data.length();i++)
{
JSONObject data1 = data.getJSONObject(i);
String ans = data1.getString("ident");
}
} catch (JSONException e) {
e.printStackTrace();
}
return ans;
}
and this JSON:
{
"SearchResult": {
"next_offset": -1,
"aircraft": [
{
"ident": "AFL274",
"type": "B77W"
},
{
"ident": "CQH8971",
"type": "A320"
}
]
}
}

Try this,
public String[] getInfo(String url) {
try {
String result = HttpGet(url);
JSONObject json = new JSONObject(result);
JSONObject val = json.getJSONObject("SearchResult");
JSONArray data = val.getJSONArray("aircraft");
int arrayLength = data.length();
String[] strAryAns = new String[arrayLength];
for(int i=0;i<arrayLength;i++)
{
JSONObject data1 = data.getJSONObject(i);
strAryAns[i] = data1.getString("ident");
}
} catch (JSONException e) {
e.printStackTrace();
}
return strAryAns;
}

Related

Java: How do I create this JSON Array Structure using GSON

I want to create a JSON array structure like this or append an object to the structure
{ "user" : [
{"name" : "user1", "email": "user1#gmail"},
{"name": "user2", "email": "user2#gmail"}
]
}
I'm using GSON to write this into a file
public void appendToObject(File jsonFile, String key, String value) {
Objects.requireNonNull(jsonFile);
Objects.requireNonNull(key);
Objects.requireNonNull(value);
if (jsonFile.isDirectory()) {
throw new IllegalArgumentException("File can not be a directory!");
}
try {
JsonObject node = readOrCreateNew(jsonFile);
JsonArray userArray = new JsonArray();
userArray.add(user(key,value));
node.add("user", userArray);
FileWriter writer = new FileWriter(jsonFile)
gson.toJson(node, writer);
}catch (Exception e)
{
Log.d("display1", "appendToObject: error"+e.getLocalizedMessage());
e.printStackTrace();
}
}
private JsonObject user(String user, String password){
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", user);
jsonObject.addProperty("password", password);
return jsonObject;
}
private JsonObject readOrCreateNew(File jsonFile) throws IOException {
if (jsonFile.exists() && jsonFile.length() > 0) {
try (BufferedReader reader = new BufferedReader(new FileReader(jsonFile))) {
return gson.fromJson(reader, JsonObject.class);
}
}
return new JsonObject();
}
Here's the code with suggestions integrated and with reading and writing JSON file functions
but im getting "user1":"{\"values\":[null,\"user13\",\"useremail13\"]}"}
how to structure it so that I get the desired output
I omitted some your code in appendToObject. But the meaning should be clear.
public void appendToObject(File jsonFile, String key, String value) {
...
JsonObject node = readOrCreateNew(jsonFile);
JsonObject newUser = user(key, value);
JsonElement user = node.get("user");
if (user != null && user.isJsonArray()){
((JsonArray) user).add(newUser);
} else {
JsonObject root = new JsonObject();
node.add("user", createArray(newUser));
}
...
}
private JsonObject createUserArray(JsonObject ... objects){
JsonArray userArray = new JsonArray();
for (JsonObject user : objects) {
userArray.add(user);
}
return userArray;
}
private JsonObject user(String email, String name){
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", name);
jsonObject.addProperty("email", email);
return jsonObject;
}

How to get the values of a key of a json file

How can i get the values of a json key in Java here is my code
private void getWebApiData() {
String WebDataUrl = "myjsonfileurl";
new AsyncHttpTask.execute(WebDataUrl);
}
#SuppressLint("StaticFieldLeak")
public class AsyncHttpTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpsURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpsURLConnection) url.openConnection();
if (result != null) {
String response = streamToString(urlConnection.getInputStream());
parseResult(response);
return result;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
newsAdapter = new NewsAdapter(getActivity(), newsClassList);
listView.setAdapter(newsAdapter);
Toast.makeText(getContext(), "Data Loaded Successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "Failed to load data!", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
}
}
private String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != stream) {
stream.close();
}
return result;
}
private void parseResult_GetWebData(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("books");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
JSONObject sourceObject = articleObject.getJSONObject("A");
String name = sourceObject.optString("name");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
My json file
{
"books": [
{
"A": [
{
"Amazonite": {
"name": "Amazonite",
"image": "www.google.com"
},
"Amethyst": {
"name": "Amethyst",
"image": "www.google.com"
}
}
],
"B": [
{
"Beryl": {
"name": "Beryl",
"image": "www.google.com"
},
"BloodStone": {
"name": "Bloodstone",
"image": "www.google.com"
}
}
]
}
]
}
What i would like is how to get the values of data under the Alphabet A that is Amazonite and Amethyst and the value of data under Alphabet B but the could i have just give me empty text field nothing no data is being populated.
I have tried with this code but the values retures "null"
private void parseResult_GetWebData(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = jsonObject.getJSONArray("books");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
String name = String.valueOf(articleObject.optJSONObject("A"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I am not sure what you really want, but if you just want to get "Amazonite and Amethyst" as you responded under OP, you can try this:
Code snippet
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject articleObject = jsonArray.getJSONObject(i);
JSONArray jsonArrayA = articleObject.getJSONArray("A");
for (int j = 0; j < jsonArrayA.length(); j++) {
JSONObject obj = jsonArrayA.getJSONObject(j);
System.out.println(obj.names());
obj.names().forEach(e -> {
System.out.println(obj.getJSONObject(e.toString()).get("name"));
});
}
}
Console output
["Amazonite","Amethyst"]
Amazonite
Amethyst
Update
I am not sure which name you want to retrieve because both Amazonite and Amethyst appear two times in JSON array A, so I provide two ways to show them as follows:
List<String> names = new ArrayList<>();
List<String> innerNames = new ArrayList<>();
for (int j = 0; j < jsonArrayA.length(); j++) {
JSONObject obj = jsonArrayA.getJSONObject(j);
JSONArray keys = obj.names();
for (int k = 0; k < keys.length(); k++) {
String name = keys.getString(k);
String innerName = obj.getJSONObject(keys.optString(k)).getString("name");
System.out.printf("name: %s, inner name: %s\n", name, innerName);
names.add(name);
innerNames.add(innerName);
}
}
System.out.println(names.toString());
System.out.println(innerNames.toString());
Console output
name: Amazonite, inner name: Amazonite
name: Amethyst, inner name: Amethyst
[Amazonite, Amethyst]
[Amazonite, Amethyst]

I have difficulty printing java json data

I currently received the json file in java, turned the json file on the formun, debugged it, and tried sysout.
The problem is, I try to output to the table in jsp, but only the last source from json comes out.
How can we solve this?
#RequestMapping(value = "spaghettiSub", method = RequestMethod.POST)
public String spaghetti(ModelMap modelMap) {
JSONParser jsonParser = new JSONParser();
try{
JSONArray page = (JSONArray) jsonParser.parse(new FileReader("d:\\spaghetti.json"));
int pageCnt = page.size();
Map<String,String> map = new HashMap<String,String>();
List<Map<String,String>> spaghettiList = new ArrayList<Map<String,String>>();
for(int i = 0; i < pageCnt; i++) {
Object obj = page.get(i);
JSONObject jsonObject = (JSONObject) obj;
String no = (String) jsonObject.get("no");
String name = (String) jsonObject.get("name");
String explanation= (String) jsonObject.get("explanation");
map.put("no", no);
map.put("name", name);
map.put("explanation", explanation);
spaghettiList.add(map);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return "sub/" + this.urlbase + "/spaghetti";
}
json
[
{
"no": "1",
"name": "Spaghettoni",
"explanation": "It is commonly used in the Carbonara Spaghetti, which is about 2mm thick."
},
{
"no": "2",
"name": "Spaghettini",
"explanation": "Spaghetti 1.6mm thick"
},
{
"no": "3",
"name": "Fedelini",
"explanation": "Spaghetti from 1.3mm to 1.5mm thick"
}]
you have to move this Map<String,String> map = new HashMap<String,String>(); inside your for loop.
Note:
As JB Nizet mentioned start using objects instead of JsonArray.
First thing first
Solve Issue
You are only getting last row in your JSP is because you have declared your Map outside of for loop.
If you are in hurry and have no time in world just move this
Map<String,String> map = new HashMap<String,String>();
inside
for(int i = 0; i < pageCnt; i++) {
This will solve your problem.
Improve your Code
But you can make it way more better and efficient by doing something like this
Define a DTO class
public class MyData {
private String no;
private String name;
private String explanation;
// getter setter
}
Use this DTO class to fill values like you did for Map
The whole code looks something like this.
#RequestMapping(value = "spaghettiSub", method = RequestMethod.POST)
public String spaghetti(ModelMap modelMap) {
JSONParser jsonParser = new JSONParser();
try{
JSONArray page = (JSONArray) jsonParser.parse(new FileReader("d:\\spaghetti.json"));
int pageCnt = page.size();
List<MyData> spaghettiList = new ArrayList<MyData>();
for(int i = 0; i < pageCnt; i++) {
MyData mydata = new MyData();
Object obj = page.get(i);
JSONObject jsonObject = (JSONObject) obj;
String no = (String) jsonObject.get("no");
String name = (String) jsonObject.get("name");
String explanation= (String) jsonObject.get("explanation");
mydata.setNo(no);
mydata.setName(name);
mydata.setExplanation(explanation);
spaghettiList.add(mydata);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return "sub/" + this.urlbase + "/spaghetti";
}

Proper way to format a JSON object and send to server via volley

I'm trying to use the Safe Browsing API from google to check if a web link is black listed, just need to send a request within a JSON object to:
POST https://safebrowsing.googleapis.com/v4/threatMatches:find?key=API_KEY HTTP/1.1
Content-Type: application/json
And the JSON object should be like:
{
"client": {
"clientId": "mycompanyname",
"clientVersion": "1.1"
},
"threatInfo": {
"threatTypes": ["MALWARE", "SOCIAL_ENGINEERING"],
"platformTypes": ["WINDOWS"],
"threatEntryTypes": ["URL"],
"threatEntries": [
{"url": "http://www.urltocheck1.org/"},
{"url": "http://www.urltocheck2.org/"},
{"url": "http://www.urltocheck3.com/"}
]
}
}
But already I don't know if I am formatting my JSON object properly, or my code is correct, see below:
public class SB {
private ArrayList<String> url; //URL's a analizar
private String key; //API key
private RequestQueue queue;
private Context context;
private ArrayList<SBthreat> AnalyzedUrl; //analysis final
private boolean Interrupted = false;
private boolean CallFail = false;
public SB(Context context, ArrayList<String> url, String key){
this.url = url;
this.key = key;
this.context = context;
queue = Volley.newRequestQueue(context);
AnalyzedUrl = new ArrayList<>();
}
public void Request(){
final StringBuilder api = new StringBuilder("https://safebrowsing.googleapis.com/v4/threatMatches:find?key=");
JSONObject requestBody = new JSONObject();
//JSON body
try {
JSONObject client = new JSONObject();
client.put("clientId", "NetworkSentinel");
client.put("clientVersion", "1.2");
JSONObject threatEntries = new JSONObject();
for(int i = 0; i < this.url.size(); i++){
threatEntries.put("url", this.url.get(i)); //-----> the url can be too many
}
JSONObject threatInfo = new JSONObject();
threatInfo.put("threatTypes", "[\"MALWARE\", \"SOCIAL_ENGINEERING\"]");
threatInfo.put("platformTypes", "[\"WINDOWS\"]");
threatInfo.put("threatEntryTypes", "[\"URL\"]");
threatInfo.put("threatEntries", threatEntries);
JSONObject jsonBody = new JSONObject();
jsonBody.put("client", client);
jsonBody.put("threatInfo", threatInfo);
requestBody.put("", jsonBody);
}catch (JSONException e) {
e.printStackTrace();
}
api.append(key).append(" HTTP/1.1");
Log.i("SB", api.toString().replace(key, "XXXXXXXXXXXXX"));
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, api.toString(), requestBody, future, future){
#Override
public HashMap<String, String> getHeaders() {
HashMap<String, String> params = new HashMap<>();
params.put("Content-Type", "application/json");
return params;
}
};
queue.add(request);
try {
JSONObject response = future.get();
if(response.length() != 0) {
Log.i("SB", "-----------------------------------------------------------------------");
Log.i("response", response.toString());
Interrupted = false;
CallFail = false;
}
} catch (InterruptedException e) {
e.printStackTrace();
Interrupted = true;
} catch (ExecutionException e) {
e.printStackTrace();
CallFail = true;
}
}
public ArrayList<SBthreat> GetAnalysis(){
return AnalyzedUrl;
}
public boolean isInterrupted(){
return Interrupted;
}
public boolean isCallFail(){
return CallFail;
}
}
Is the code threatInfo.put("threatTypes", "[\"MALWARE\", \"SOCIAL_ENGINEERING\"]"); well written? Or is there is a better way to put data in square brackets?
When I run my code always get the error com.android.volley.ClientError and connections errors, what I'm doing wrong?
You should use JSONArray and don't use [ ] to place manually. Please refer below:
JSONObject client = new JSONObject();
client.put("clientId", "mycompanyname");
client.put("clientVersion", "1.1");
JSONObject threatInfo = new JSONObject();
JSONArray threatTypes = new JSONArray();
threatTypes.put("MALWARE");
threatTypes.put("SOCIAL_ENGINEERING");
JSONArray platformTypes = new JSONArray();
threatTypes.put("WINDOWS");
JSONArray threatEntryTypes = new JSONArray();
threatTypes.put("URL");
JSONArray threatEntries = new JSONArray();
for(int i = 0; i < this.url.size(); i++){
JSONObject threatEntry = new JSONObject();
threatEntry.put("url", this.url.get(i)); //-----> the url can be too many
threatEntries.put(threatEntry);
}
threatInfo.put("threatTypes", threatTypes);
threatInfo.put("platformTypes", platformTypes);
threatInfo.put("threatEntryTypes", threatEntryTypes);
threatInfo.put("threatEntries", threatEntries);

Error while getting JSONArray from JSONObject

I'm trying to get a JSONArray from JSONObject, but get "Can't create JSONArray" in LogCat.
The error appears here:
JSONArray array = response_object.getJSONArray("post");
Here is my code:
try {
int id;
String author;
String authorUniqueId;
String authorPhotoUrl;
String message;
String createTime;
JSONObject response_object = new JSONObject(response);
JSONArray array = response_object.getJSONArray("post");
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = array.getJSONObject(i);
id = jsonObject.getInt("id");
author = jsonObject.getString("author");
authorUniqueId = jsonObject.getString("author_unique_id");
authorPhotoUrl = jsonObject.getString("author_photo_url");
message = jsonObject.getString("message");
createTime = jsonObject.getString("created_at");
Log.e("NewsActivity", "Added:" + author);
data.add(new NewsDataModel(id, author, authorUniqueId, authorPhotoUrl, message, createTime));
}
} catch (Exception e) {
Log.e(TAG, "Can't create JSONArray");
}
And my JSON:
{"error":false}
{"post":[
{
"id":"6",
"author":"NAME..."
"author_unique_id":"ID...",
"message":"MESSAGE...",
"created_at":"TIME...",
"author_photo_url":"URL..."
},
{
"id":"5",
"author":"NAME..."
"author_unique_id":"ID...",
"message":"MESSAGE...",
"created_at":"TIME...",
"author_photo_url":"URL..."
},
{
"id":"4",
"author":"TEXT..."
"author_unique_id":"ID...",
"message":"MESSAGE...",
"created_at":"TIME...",
"author_photo_url":"URL..."
}
]}

Categories