Iterate over Json response with Multiple JSONArray And JSONObject - json

{
"Response":"success",
"errorText":null,
"TotalBooks":null,
"privateBookStore":{
"privateBooks":[
{
"Shopid":76354,
"Shopname":"xyz",
"Term":null,
"“Strategy":[
{
"Name":"ABC",
"ID":9
}
],
"magaerTYpe":"Single",
"Freq":"”monthly”",
"StructureType":{
"Name":"ABC",
"ID":9
},
"Currency":[
"USD",
"EURO",
"RUPYEE"
]
}
]
}
}
I have tried with JsonObject and JsonArray but the format of response is containing multiple JsonArray and JsonObject Together
I tried using HashMap and List but its not working for me. Loop through multiple JsonObject I have gone though this too.
Kindly suggest the approach
What I have so far is -
inputstream in = new bufferedinputstream(urlconnection.getinputstream());
String result = ioutils.tostring(in utf-8 );
JSONObject outer = new JSONObject(result);
JSONObject inner = outer.getJSONObject("privateBookStore");
JSONArray arr = inner.getJSONArray("privateBooks");
also tried with this too but not giving me key:value pair structure
List<HashMap<String,String>> response = new ArrayList<>();
JSONArray jsonarray = null;
try {
jsonarray = new JSONArray(json);
for(int i=0;i<jsonarray.length();i++) {
JSONObject jsonObject = jsonarray.getJSONObject(i);
Iterator<?> iterator = jsonObject.keys();
HashMap<String,String> map = new HashMap<>();
while (iterator.hasNext()) {
Object key = iterator.next();
Object value = jsonObject.get(key.toString());
map.put(key.toString(),value.toString());
}
response.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}

Related

JSONArray cannot be converted to JSONObject in Asynctask

I am trying to Parse JSON Data get From URL and Insert Data to Firebase from response using asynctask.Below is the code I have written but it is not inserting any data to Firebase.My Firebase Reference is correct as I log.e Below is the code
JSONArray arr = new JSONArray(result);
mDatabase = FirebaseDatabase.getInstance().getReference().child(context.getResources().getText(R.string.bid_request).toString().trim()).child("b");
for(int i=0; i < arr.length(); i++) {
JSONObject obj = arr.getJSONObject(i);
Map<String, Object> userValues = new HashMap<>();
final String node = obj.getString("mysql_id");
final String id = obj.getString("id");
DatabaseReference newBid = mDatabase.child(node);
String data = obj.getString("new_comer");
String[] items = data.split(",");
for (String item : items) {
userValues.put(item, 1);
}
serValues.put("tReq", obj.getString("tReq"));
newBid.setValue(userValues, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!=null){
Log.e("error", "onComplete: "+databaseError);
}
}
});
And below is the Error showing in my log.Can not figure out what is wrong I am doing
E/myapp: onPostExecute: org.json.JSONException: Value [{"id":"14248","mysql_id":"a6555018-de41-4fc7-942e-530389aa3a9d","tReq":"4","new_comer":"10019,10029"}] at 0 of type org.json.JSONArray cannot be converted to JSONObject

Here i want to pass each json object to another activity and set that object value to some textview

pass the vehiclename object to another activity
and set that value as a text view
Please Help Me
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
public void onResponse(JSONObject response) {
try {
JSONObject object1 = response.getJSONObject("liveMapResponseVO");
JSONArray jsonArray = object1.getJSONArray("locations");
for(int i=0; i<jsonArray.length(); i++){
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
Movie movie = new Movie();
movie.setTitle(jsonObject.getString("vehicleName"));
movie.setRating(jsonObject.getString("speed"));
movie.setGenre(jsonObject.getString("stopTime"));
movie.setYear(jsonObject.getString("idleTime"));
Log.d(TAG, jsonObject.getString("vehicleName"));
movieList.add(movie);
}
pDialog.hide();
} catch (JSONException e) {
e.printStackTrace();
}
adapter.notifyDataSetChanged();
}

JSON object in for loop keeps only last record

I have this code
JSONObject output = new JSONObject();
JSONObject elements = new JSONObject();
JSONArray jsonArrayOutput = new JSONArray();
ArrayList<String> name = ArrayList<String>();
for (int i=0 ; i<name.size() ; i++){
elements.put("Name", name.get(i));
jsonArrrayOutput.put(elements);
}
output.put("Results", jsonArrrayOutput).toString();
The problem is that the resulted output Json has only the last element of "name" arraylist many times, not all elements.
How can I fix it?
You are adding elements again same name key in jsonArrayOutput
try creating a new JSONObject for each iteration.
E.g.:
JSONObject output = new JSONObject();
JSONObject elements = new JSONObject();
JSONArray jsonArrayOutput = new JSONArray();
ArrayList<String> name = ArrayList<String>();
for (int i=0 ; i<name.size() ; i++){
JSONObject temp = new JSONObject();
temp.put("Name", name.get(i));
jsonArrrayOutput.put(temp);
}
output.put("Results", jsonArrrayOutput).toString();
Here is my version of your code. The problem with your code is the declaration of your elements object. Whenever you changed the elements that would change the element and the element that you added to the array.
This happens because reference is used when you put the element object into the jsonArrayOutput
JSONObject output = new JSONObject();
JSONArray jsonArrayOutput = new JSONArray();
ArrayList<String> name = new ArrayList<>();
for (int i = 0; i < name.size(); i++) {
JSONObject elements = new JSONObject();
try {
elements.put("Name", name.get(i));
jsonArrayOutput.put(elements);
} catch (JSONException e) {
e.printStackTrace();
}
}
try {
output.put("Results", jsonArrayOutput).toString();
Log.i("info",output.toString());
} catch (JSONException e) {
e.printStackTrace();
}
Hope that helps!

Java save json byte array image to particular location

I have one application that posts json data like below
{
"image": "data:image/png;base64,eAvQPaQEJCABCUjg/wNeEta73J3yXwAAAABJRU5ErkJggg==................"
}
It posts image(png or jpg) base64 byte array in the "image" key.
I want to save that image under the name "datetime.png" into my specified location.
For this I am using the code below:
#POST
#Consumes("application/x-www-form-urlencoded")
#Path("/getImage")
public Response GetImage(String json) {
java.util.Date dt = new java.util.Date();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
String currentTime = sdf.format(dt);
JSONObject returnJson = new JSONObject();
try {
JSONObject innerJsonObj = new JSONObject(json);
String imageCode=innerJsonObj.getString("image");
String base64Image = imageCode.split(",")[1];
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);
FileOutputStream fos = new FileOutputStream("D:\\image\\" + currentTime + ".png");
try {
fos.write(imageBytes);
} finally {
fos.close();
}
returnJson.put("success", true);
} catch (Exception e) {
JSONObject errorJson = new JSONObject();
errorJson.put("success", false);
return Response.ok(errorJson.toString()).header("Access-Control-Allow-Origin", "*").build();
}
return Response.ok(returnJson.toString()).header("Access-Control-Allow-Origin", "*").build();
}
But it gives me the following Error
java.io.FileNotFoundException: D:\image\2016-07-15 17:04:34.png (The
filename, directory name, or volume label syntax is incorrect)

Add Json file contents to JsonObject in Java

I have a Json file E:\\jsondemo.json in disk. I want to create JSONObject in Java and add the contents of the json file to JSONObject. How it is possible?
JSONObject jsonObject = new JSONObject();
After creating this objec, what should i do to read the file and put values in jsonObject
Thanks.
You can transform a file in a String using a function proposed in this question:
private static String readFile(String path) throws IOException {
FileInputStream stream = new FileInputStream(new File(path));
try {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
/* Instead of using default, pass in a decoder. */
return Charset.defaultCharset().decode(bb).toString();
}
finally {
stream.close();
}
}
After getting the string, you can transform it to a JSONObject with the following code:
String json = readFile("E:\\jsondemo.json");
JSONObject jo = null;
try {
jo = new JSONObject(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In the above example, I used this library, very simple to learn. You can add values to your JSON object in this way:
jo.put("one", 1);
jo.put("two", 2);
jo.put("three", 3);
You can also create JSONArray objects, and add it to your JSONObject:
JSONArray ja = new JSONArray();
ja.put("1");
ja.put("2");
ja.put("3");
jo.put("myArray", ja);