How to set JSONObject to textview - java

I have been trying to set textview to "name" value from the json array responds but not working but if I run this code
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//view_member__progressBar.setVisibility(View.GONE);
try {
JSONObject object = new JSONObject(s);
detail.setText(object.getString("customer"));
} catch (JSONException e) {
e.printStackTrace();
}
}
I will get this result
{"name":"Adene Jonah","address":"Mr. John Doe 34 Tokai, Abuja. 7999.","util":"Demo Utility","minimumAmount":"500"}
but if I run this code below I will get nothing
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//view_member__progressBar.setVisibility(View.GONE);
try {
JSONObject object = new JSONObject(s);
JSONArray ar = new JSONArray();
ar =object.getJSONArray("customer");
detail.setText(ar.getString(0).);
} catch (JSONException e) {
e.printStackTrace();
}
}
this is the value of s
{"status":"00","message":"OK","access_token":"22071108062392","customer":{"name":"Adene Jonah","address":"Mr. John Doe
34 Tokai, Abuja. 7999.","util":"Demo
Utility","minimumAmount":"500"},"response_hash":"4a0d9cf3a7d63c5b0f9087931bef5540a0665add"}

First of all, there is no json array inside your json content. Json array is an array inside the json content. No such array exists in your json content. To give an example, assuming the name field is inside an array. It should have looked like this then:
{
"name": [
{
"personName": "Adene Jonah"
},
{
"personName": "abc"
}
],
"address": "Mr. John Doe 34 Tokai, Abuja. 7999.",
"util": "Demo Utility",
"minimumAmount": "500"
}
A json array starts with a [ sign and actually encloses many arrays. So if we give an example on the name field, it can contain many names. But your json content is a pure json object. You can check this from sites like these. JSON Beautifier

Related

How to create and append to a JSON file iteratively?

My test class calls the addEachEmployeeDetailsToJSONFile method multiple times during the execution with different employee details.
The expected end result is a JSON file named mapping.json that looks like below:
EXPECTED mapping.json
[
{
"employee": {
"ID": "123",
"Name": "Gupta",
"Department": "Accounts"
}
},
{
"employee": {
"ID": "456",
"Name": "Mark",
"Department": "Marketing"
}
}
]
Below is my Java class.
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import java.io.*;
public class Test {
private String filePath = new File("").getAbsolutePath() + File.separator + "target" + File.separator + "mapping.json";
protected JSONObject employeeDetails = new JSONObject();
protected JSONObject employeeObject = new JSONObject();
protected JSONArray employeeList = new JSONArray();
private FileWriter fileWriter;
{
try {
fileWriter = new FileWriter(getMappingFile(), true);
} catch (IOException e) {
e.printStackTrace();
}
}
//Write to JSON file
private File getMappingFile (){
File mappingFile = new File(getMappingFilePath);
mappingFile.setWritable(true);
mappingFile.setReadable(true);
return mappingFile;
}
public void addEachEmployeeDetailsToJSONFile(ITestContext iTestContext) {
try {
//Write to first JSONObject
employeeDetails.put("ID", iTestContext.getId());
employeeDetails.put("Name", iTestContext.getName());
employeeDetails.put("Department", iTestContext.getDepartment());
//Put the above JSON Object in another JSON object.
employeeObject.put("employees", employeeDetails);
//Write above object to JSONArray
employeeList.add(employeeObject);
//We can write any JSONArray or JSONObject instance to the file
fileWriter.append(beforeTestClassesList.toJSONString());
}
catch (Exception e)
{}
}
public static void main( String[] args )
{
addEachEmployeeDetailsToJSONFile(<pass employee Gupta instance>);
addEachEmployeeDetailsToJSONFile(<pass employee Mark instance>);
fileWriter.flush();
}
}
The JSON file is being created successfully and an entry is also being created like below, but, only the first entry of one employee details is being created and not a list of multiple employees and their details. What am I missing?
Current mapping.json file:
[
{
"employee": {
"ID": "123",
"Name": "Gupta",
"Department": "Accounting"
}
}
]
Your code as shown only adds 1 item. So this is as expected. Also, you would create a new JSON object for each employee, not reuse the same one repeatedly. That will cause problems on subsequent saves. Further, your code is really a bit poorly architected. Due to the nature of JSON, appending to a file isn't really done. You write the entire file at once. This means you don't write until you have all the data, you don't write after adding each item to the array. The reason for this is that there's data after the element in the array to make it valid JSON, and you can't stick stuff in the middle of a file. Appending to a JSONArray in memory is fine, but when writing to disk you want to write the entire file.

Create a Validation that will take jsonPath and type, Check whether the data type is same for the jsonpath and the type

I am reading one file, IN that Json data is available.
I need to create a method, Which takes jsonobject, jsonpath,type
I need to check the datatype of jsonpath, type...If the datatype is same it should return true else false...
Example : store.book[0].title.... this is the jsonpath and it will return title value as a string
so if the type which we given as a string ...it should return true..
Json Data :
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
},
"expensive": 10
}
This the java Code for reading the Json file and getting the output..
Example : store.book[0].title.... this is the jsonpath and it will return title value as a string,
so if the type which we given as a string ...it should return true..
public class Validation {
public void readJSON() throws Exception {
File file = new File("myJSONFile.txt");
String content = FileUtils.readFileToString(file, "utf-8");
// Convert JSON string to JSONObject
JSONObject tomJsonObject = new JSONObject(content);
System.out.println(tomJsonObject);
System.out.println(tomJsonObject.getString("age"));
//validateByType(tomJsonObject, "age", null);
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Test");
Validation v = new Validation();
try {
v.readJSON();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Why not create objects wrt the JSON? So that you can check for null! You can do it by creating Object classes with reference to the fields available in the JSON, and generate getters and setters for the fields in the object classes. So, that you may use the objects globally. Object creation sample here and also in this question.

How to Parse Json Objects of Json Object and of Object (outdated) [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
I'm trying to parse multiple objects,Bellow i'm receiving Json Sample The requirement completed and my question now outdated, can someone please up-vote to help me for asking next question? Will he helpfull for and thanks for
{
"0": //outer objects are multiples, i just post one object for sample
{
"id": "1",
"name": "B2 MR1",
"description":
{
"0": //it is also multiple objects m just showing one
{
"title": "Carve the Future",
"description": "Welcome to Meeting Room 1",
"push_notification": "Carve the Future",
}
}
},//after that the next obj will be show
.
.
}
In second object 1 i also have above keys and values, i can't handel it, here is my Model.
public class JsonModel {
private String id; //getter setter
private String name; //getter setter
List<InnerDescprtion> description; //getter setter
}
Here is my InnerDescprtion Model
private class InnerDescprtion {
private String id; //getter setter
private String title; //getter setter
}
And below is my java code for parsing it using Gson,
JsonModel outterModelClass= null;
List<JsonModel> listObj = new ArrayList<>();
for (int i = 0; i < responseJson.length(); i++) {
try {
outterModelClass= new Gson().fromJson(responseJson.getString(String.valueOf(i)), JsonModel.class);
listObj.add(outterModelClass); //here i'm getting exception,,
} catch (JSONException e) {
e.printStackTrace();
}
}
I get the solution, Please up-vote to help me.
If it is possible for you I would change the json to something like this:
[{
"id": "1",
"name": "B2 MR1",
"description": [{
"id" : "1-1",
"title": "Carve the Future",
"description": "Welcome to Meeting Room 1",
"push_notification": "Carve the Future"
}]
},
{
"id": "2",
"name": "B2 MR2",
"description": [{
"id" : "2-1",
"title": "Carve the Future 2",
"description": "Welcome to Meeting Room 2",
"push_notification": "Carve the Future 2"
}]
}
]
Then your approach should work with just a few changes:
BufferedReader br = new BufferedReader(new FileReader("c:/test/test.json"));
Type listType = new TypeToken<ArrayList<JsonModel>>(){}.getType();
List<JsonModel> outterModels = new Gson().fromJson(br, listType);
If you can't change the json I would suggest to use another JSON library like json simple and extract everything manually.
Your 'listObj' should be defined this way:
ArrayList<JsonModel> listObj = new ArrayList<JsonModel>();
Well that is a nasty looking JSON. However I recommend you use volley android library. I had a task with somewhat similar problem. Only there was a single object inside of another object. To include volley in your project, update your build.gradle app module with compile 'com.android.volley:volley:1.0.0' inside dependencies{}. baseUrl is the url where you are fetching the JSON from.
Then you can do something like:
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
baseUrl,
null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
// Parsing json object response
// response will be a json object
for (int i=0; i<response.length(); i++){
JSONObject obj = response.getJSONObject(i);
//id
//name
try{
for (int j=0; j<obj.length() ; j++) {
JSONObject description = obj.getJSONObject(j);
//title
//description
//push notification
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
hidepDialog();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
VolleyLog.d(TAG,"Error: "+ volleyError.getMessage() );
Toast.makeText(getApplicationContext(), volleyError.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
//adding request to request queue
AppController.getmInstance().addToRequestQueue(jsonObjReq);
Add this in your parseJSON(){} method or whatever you've named it.
I have not tried doing what you are trying do to. But it seems doable, with the use of volley library.

How do I get data from JSON string?

Here is my code:
try {
JSONObject json = (JSONObject) new JSONTokener(result).nextValue();
System.out.println(json);
JSONObject json2 = json.getJSONObject("data");
String test = json2.getString("headline");
System.out.println(test);
} catch (JSONException e) {
e.printStackTrace();
}
My String values start with the object data. So I am trying to get that object first and then capture the the object headline inside that.
My problem is, it is not taking the object data from the string.
Once I reach the line JSONObject json2 = json.getJSONObject("data");, it throws the exception. Please shed some light on this.
"data": [
{
"headline": "Close Update"
"docSource": "MIDNIGHTTRADER",
"source": "MTClosing",
"dateTime": "2015-10-23T16:42:46-05:00",
"link": "Markets/News",
"docKey": "1413-A1067083-1B14K77PVTUM1O7PCAFMI3SJO4",
},
The value for the key data is a JSON array containing one object, and not an object itself.
To get that object inside data, replace your line that throws an exception with the following:
JSONObject json2 = json.getJSONArray("data").get(0);
This gets the data array as a JSONArray object and then gets the 0th element, which is the object you want.
Your data "object", isn't actually an object, it's an array, notice the opening square bracket... I'm assuming in your actual code, it closes with one too.
"data": [{
"headline": "Close Update"
"docSource": "MIDNIGHTTRADER",
"source": "MTClosing",
"dateTime": "2015-10-23T16:42:46-05:00",
"link": "Markets/News",
"docKey": "1413-A1067083-1B14K77PVTUM1O7PCAFMI3SJO4",
}]
Try json.getJSONArray("data")[0] instead... or whatever index you need
try {
JSONObject json = (JSONObject) new JSONTokener(result).nextValue();
System.out.println(json);
JSONObject json2 = json.getJSONArray("data")[0];
String test = json2.getString("headline");
System.out.println(test);
}
catch (JSONException e) {
e.printStackTrace();
Your problem is based on the fact that your service returns and array instead of a single json object, so from here you can follow this suggestions to process directly from the JSONArray Can't access getJSONArray in java, or, at server side you can encapsulate your response array into another object like this (java example):
public class Data<T> {
private List<T> elements;
public ObjectSugetionsDTO(){
And build the response like this:
return new ResponseEntity<Data<YourInternalRepresentation>>(
new Data<YourInternalRepresentation>(yourMethodCallForTheArray()),
HttpStatus.OK);
I have found the second way to be better at keeping my API cleaner and more readable
EDIT: Better way
I whould also suggest the use of retrofit (http://square.github.io/retrofit/), by doing so, your service calls is resumed to (Example of calling and API that retrieves a list of users):
public class UserService {
public static IUserService getUserService() {
return RestAdapterManager.createService(IUserService.class );
}
public interface IUserService{
#GET("/api/users")
public void getAllUsers(Callback<List<User>> callback);
}
}
and the service call itself
UserService.getUserService().getAllUsers(new Callback<List<User>>() {
#Override
public void success(List<User> users, Response response) {
Log.d("Exito! " , "" + users.size());
}
#Override
public void failure(RetrofitError error) {
Log.d("Fail!", error.getUrl());
}
});
The simple inicialization of the connection object
public static <S> S createService(Class<S> serviceClass, String username, String password) {
RestAdapter.Builder builder = new RestAdapter.Builder()
.setEndpoint(API_BASE_URL);//Your api base url
RestAdapter adapter = builder.setLogLevel(RestAdapter.LogLevel.FULL).build(); //change the logging level if you need to, full is TOO verbose
return adapter.create(serviceClass);
}

Error while creating a sub JSONObject from another JSONObject

I am working on an Android app and one of its functionnalities is to know when a streamer is streaming by using Twitch API.
When a streamer is streaming, if I connect to https://api.twitch.tv/kraken/streams/ I get a String which I use to build a JSON object like that :
{
"_links":{
"self":"https://api.twitch.tv/kraken/streams/srkevo1",
"channel":"https://api.twitch.tv/kraken/channels/srkevo1"
},
"stream":{
"_id":15361851552,
"game":"Super Smash Bros. for Wii U",
"viewers":42613,
"created_at":"2015-07-18T15:07:59Z",
"video_height":720,
"average_fps":59.319897084,
"_links":{
"self":"https://api.twitch.tv/kraken/streams/srkevo1"
},
"preview":{
"small":"http://static-cdn.jtvnw.net/previews-ttv/live_user_srkevo1-80x45.jpg",
"medium":"http://static-cdn.jtvnw.net/previews-ttv/live_user_srkevo1-320x180.jpg",
"large":"http://static-cdn.jtvnw.net/previews-ttv/live_user_srkevo1-640x360.jpg",
"template":"http://static-cdn.jtvnw.net/previews-ttv/live_user_srkevo1-{width}x{height}.jpg"
},
"channel":{
"_links":{
"self":"https://api.twitch.tv/kraken/channels/srkevo1",
"follows":"https://api.twitch.tv/kraken/channels/srkevo1/follows",
"commercial":"https://api.twitch.tv/kraken/channels/srkevo1/commercial",
"stream_key":"https://api.twitch.tv/kraken/channels/srkevo1/stream_key",
"chat":"https://api.twitch.tv/kraken/chat/srkevo1",
"features":"https://api.twitch.tv/kraken/channels/srkevo1/features",
"subscriptions":"https://api.twitch.tv/kraken/channels/srkevo1/subscriptions",
"editors":"https://api.twitch.tv/kraken/channels/srkevo1/editors",
"videos":"https://api.twitch.tv/kraken/channels/srkevo1/videos",
"teams":"https://api.twitch.tv/kraken/channels/srkevo1/teams"
},
"background":null,
"banner":null,
"broadcaster_language":"en",
"display_name":"srkevo1",
"game":"Super Smash Bros. for Wii U",
"logo":"http://static-cdn.jtvnw.net/jtv_user_pictures/srkevo1-profile_image-e46c53476d9b74c7-300x300.png",
"mature":null,
"status":"Evolution 2015 - Main Stage (July 17-19) all brackets http://evo2015.s3.amazonaws.com/brackets/index.html",
"partner":true,
"url":"http://www.twitch.tv/srkevo1",
"video_banner":"http://static-cdn.jtvnw.net/jtv_user_pictures/srkevo1-channel_offline_image-ee2fc39d6ebb7735-640x360.jpeg",
"_id":30917811,
"name":"srkevo1",
"created_at":"2012-05-30T16:57:11Z",
"updated_at":"2015-07-18T16:18:40Z",
"delay":0,
"followers":82134,
"profile_banner":null,
"profile_banner_background_color":null,
"views":20938144,
"language":"en"
}
}
}
This is how I get the JSON Object :
public class GetStreamStatus extends AsyncTask<Void,Void,String> {
#Override
protected String doInBackground(Void... params) {
String res = bibixChannel.getJson("streams");
return res;
}
#Override
protected void onPostExecute(String s) {
channelStatusString = s;
channelStatusObject = bibixChannel.buildJSON(s);
}
}
The buildJson() method is simply :
protected JSONObject buildJSON(String jsonRaw){
JSONObject json = null;
try{
json = new JSONObject(jsonRaw);
}catch (Exception e){
e.printStackTrace();
}
return json;
}
But after, to know if the streamer is streaming, a part of the JSON string is nulled like that :
If the streamer is streaming, you will get the fist JSON I wrote on the top of that post, else you will get something like that :
{
"_links":{
"self":"https://api.twitch.tv/kraken/streams/bibixhd",
"channel":"https://api.twitch.tv/kraken/channels/bibixhd"
},
"stream":null
}
What I want to do is getting the "stream" part in another instance variable to either recover infos about the stream or to display an offline message.
What i have got from your OP is that the channelStatusObject return you the JSONObject which contains stream key. Now what you want to check is that whether this stream is null or not. So you could do something like :-
protected JSONObject checkStream(JSONObject parentObject){
JSONObject json = (JSONObject) parentObject.get("stream");
return json; // will return null if stream is null else stream JSONObject
}
You can use this method & check its return value to see if stream is null or not.

Categories