Information from API - JSON - android

I try to get information from this link
and I don't get it !
This is my code:
String s = getJSONFile();
String myDataArray[] = {};
try{
JSONObject reportJSON = new JSONObject();
JSONArray dateJSON = reportJSON.getJSONArray("terrestrial_date");
myDataArray = new String[dateJSON.length()];
for (int i = 0; i <dateJSON.length(); i++){
JSONObject jsonObject = dateJSON.getJSONObject(i);
myDataArray[i] = jsonObject.getString("terrestrial_date");
}
}catch (JSONException e){
e.printStackTrace();
}
ArrayAdapter<String> stringAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.row, myDataArray);
if (mListView != null){
mListView.setAdapter(stringAdapter);
}
}
this is the getJSONFile method:
public String getJSONFile() {
String json = null;
try {
InputStream is = getResources().openRawResource(R.raw.weather_json);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
Thanks for help :)

You should use GSON librari and for the Model of this code http://www.jsonschema2pojo.org/
This is so easy.

terrstial_date is a String of report. try this,
String date=jsonObject.getString("terestial_date");
also your json parsing structere is not correct accroding to your json
{
"report": {
"terrestrial_date": "2017-10-13",
"sol": 1844,
"ls": 73.0,
"min_temp": -81.0,
"min_temp_fahrenheit": -113.8,
"max_temp": -28.0,
"max_temp_fahrenheit": -18.4,
"pressure": 869.0,
"pressure_string": "Higher",
"abs_humidity": null,
"wind_speed": null,
"wind_direction": "--",
"atmo_opacity": "Sunny",
"season": "Month 3",
"sunrise": "2017-10-13T10:59:00Z",
"sunset": "2017-10-13T22:43:00Z"
}
}

This is how you can get response from OkHttp
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://marsweather.ingenology.com/v1/latest/?format=json")
.get()
.build();
try {
Response response = client.newCall(request).execute();
String json = response.body().string();
JSONObject jsonObject = new JSONObject(json);
JSONObject reportJson = jsonObject.getJSONObject("report"); // your report object.
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}

Put your Json file in your assets folder with .json extension and use this method to get JsonString from it
public String loadJSONFromAsset(String fileName) {
String json = null;
try {
InputStream is = getAssets().open(fileName);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
And get the String using this function like this
String jsonString = MyApplication.loadJSONFromAsset(this,"yourJsonFileName.json");
and Parse like that
try{
JSONObject responce = new JSONObject(jsonString);
JSONArray report= responce.getJSONObject("report");
String terrestrial_date = report.getString("terrestrial_date");
}catch (JSONException e){
e.printStackTrace();
}

this is my code after all the change:
public void find_weather() {
String url = "http://marsweather.ingenology.com/v1/latest/?format=json";
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject main_object = response.getJSONObject("results");
JSONArray array = response.getJSONArray("");
JSONObject object = array.getJSONObject(0);
String date = object.getString("date");
String tempMin = String.valueOf(main_object.getDouble("min_temp"));
String tempMax = String.valueOf(main_object.getDouble("max_temp"));
String atmo_opacity = object.getString("atmo_opacity");
mMaxTemp.setText("max_temp");
mMinTemp.setText("min_temp");
mAtmoOpacity.setText("atmo_opacity");
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEEE-MM-dd");
String formatted_data = sdf.format(calendar.getTime());
mDate.setText(formatted_data);
double temp_max_int = Double.parseDouble(tempMax);
double temp_min_int = Double.parseDouble(tempMin);
mMaxTemp.setText(String.valueOf(i));
mMinTemp.setText(String.valueOf(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(jor);

You are doing in wrong way
1.report is a JsonObject inside your response means you have your report inside another JsonObject. First you have to parse your response to get report data
2.terrestrial_date is a string data so you have to use report.getJsonString("terrestrial_date") you are using reportJSON.getJSONArray("terrestrial_date"); which is used for Array data
For, more information get a look here How to parse JSON in Android
Try this,
String s = getJSONFile();
String terrestrial_date = "";
try{
JSONObject responce = new JSONObject(s);
JSONObject report= responce.getJSONObject("report");
terrestrial_date = report.getString("terrestrial_date");
}catch (JSONException e){
e.printStackTrace();
}
EDIT
Try, Volley for fetching JSON data
First you need to add dependency of volley in build.gradle file-:
dependencies {
compile 'com.android.volley:volley:1.0.0'
}
Then use following code to fetch or parse your JSON data
// Tag used to cancel the request
String url = "http://marsweather.ingenology.com/v1/latest/?format=json";
StringRequest strReq = new StringRequest(Request.Method.GET,
url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response.toString());
String terrestrial_date = "";
try{
JSONObject responce = new JSONObject(response);
JSONObject report= responce.getJSONObject("report");
terrestrial_date = report.getString("terrestrial_date");
}catch (JSONException e){
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.getMessage());
}
});
// Adding request to request queue
Volley.newRequestQueue(this).add(strReq);
SCREENSHOT
As, You can see the screenshot above. I am getting response with the same code

Related

Android type mismatch error in Json

**I think I am facing problem on passing GET request to youtube for JSON list
**public class GetYouTubeUserVideosTask implements Runnable {
public static final String LIBRARY = "Library";
private final Handler replyTo;
private final String username;
public HttpUriRequest request;
public GetYouTubeUserVideosTask(Handler replyTo, String username) {
this.replyTo = replyTo;
this.username = username;
}
#Override
public void run() {
try {
HttpClient client = new DefaultHttpClient();
HttpUriRequest request = new HttpGet("https://gdata.youtube.com/feeds/api/videos?author=" +username+"PL25zD6TOnoFVKHbBRCaUfkgS00d1It2h9");
HttpResponse response = null;
response = client.execute(request);
String jsonString = StreamUtils.convertToString(response.getEntity().getContent());
JSONObject json = new JSONObject(jsonString);
JSONObject response1 = json.getJSONObject("response");
JSONArray jsonArray = response1.getJSONArray("items");
List<Video> videos = new ArrayList<Video>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String title = jsonObject.getString("title");
Log.i("...........",title);
String url;
try {
url = jsonObject.getJSONObject("player").getString("mobile");
} catch (JSONException ignore) {
url = jsonObject.getJSONObject("player").getString("default");
}
String thumbUrl = jsonObject.getJSONObject("thumbnail").getString("sqDefault");
videos.add(new Video(title, url, thumbUrl));
}
Library lib = new Library(username, videos);
Bundle data = new Bundle();
data.putSerializable(LIBRARY, lib);
Message msg = Message.obtain();
msg.setData(data);
replyTo.sendMessage(msg);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} catch (JSONException e2) {
e2.printStackTrace();
}
I am new to android and I am trying to parse JSON but getting type mismatch error. please help me out.
I don't know where I am getting wrong. My logcat is
11-12 07:45:59.953 27498-28258/com.example.titus.abc
W/System.err: org.json.JSONException: Value (JSONObject.java:159) 11-12 07:45:59.953
27498-28258/com.example.titus.abc W/System.err: at
org.json.JSONObject.(JSONObject.java:172) 11-12 07:45:59.953
27498-28258/com.example.titus.abc W/System.err: at
com.example.titus.abc.GetYouTubeUserVideosTask.run(GetYouTubeUserVideosTask.java:48)

Read JSON file to ArrayList

I'm having trouble loading objects from an JSON file, the idea is to store objects in the JSON file and return an array of objects, is there any easier way doing this? Or is there any better solution than JSON for doing this?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_list);
TextView studentlistTextView = (TextView)findViewById(R.id.studentlistTextView);
ArrayList<students> studentArray = loadJSONFromAsset();
try {
studentlistTextView.setText(studentArray.get(0).getName());
}catch(Exception e){
e.printStackTrace();
}
}
public ArrayList<students> loadJSONFromAsset() {
ArrayList<students> studentArray = new ArrayList<>();
String json = null;
try {
InputStream is = getAssets().open("jsonstudent");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
try {
JSONObject obj = new JSONObject(json);
JSONArray m_jArry = obj.getJSONArray("students");
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
students student = new students();
student.setName(jo_inside.getString("name"));
student.setLastname(jo_inside.getString("lastname"));
student.setNumber(jo_inside.getString("number"));
studentArray.add(student);
}
} catch (JSONException e) {
e.printStackTrace();
}
return studentArray;
}
}
This is my JSON file
{ "student" : [
{"name" : "hans", "lastname" : "rosenboll", "number" : "5325235" }
]}
You can use Gson and Shared Preference to store objects in the JSON file and return an array of objects:
private final String PERSONAL_INFO = "personal_info";
public void putPersonalInfo(Profile info) {
Gson gson = new Gson();
String json = gson.toJson(info);
getAppPreference().edit().putString(PERSONAL_INFO, json).commit();
}
public Profile getPersonalInfo() {
Gson gson = new Gson();
return gson.fromJson(getAppPreference().getString(PERSONAL_INFO, null), Profile.class);
}

HttpUrlConnection post request issue

i have issue with post request. Server gets me response message ok, but doesn't recognize json what i send as post body. I have tried almost everything. Php attribute $_POST is always empty.
Thank for your answers.
Json has structure :
{
"data": {
"email": "something#something.com",
"password": "tralala"
}
}
Android code :
public static Pair<Integer, String> signUpByEmailPost(String username, String passwd) {
try {
URL url = new URL(SERVER_URL + "create/createUser.php");
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
urlConn.setUseCaches(false);
urlConn.connect();
JSONObject json = createJsonCredentials(username, passwd);
String dataString = json.toString();
Log.i(TAG, dataString);
OutputStreamWriter out = new OutputStreamWriter(urlConn.getOutputStream());
out.write(dataString);
out.flush();
int httpResult = resolveHttpResponseCode(urlConn);
if(httpResult > 0) {
return new Pair<>(httpResult, null);
}
String receivedDataString = getStringContentFromConnection(urlConn);
return new Pair<>(0, receivedDataString);
} catch (Exception e) {
e.printStackTrace();
}
return new Pair<>(3, null);
}
private static JSONObject createJsonCredentials(String username, String password) {
try {
JSONObject jsonInner = new JSONObject();
jsonInner.put("email", "something#something.com");
jsonInner.put("password", "tralala");
JSONObject jsonOuter = new JSONObject();
jsonOuter.put("data", jsonInner);
return jsonOuter;
} catch(JSONException ex) {
ex.printStackTrace();
}
return null;
}
Server response :
{
success: false,
errors: {
email: "blank_email",
password: "blank_password"
}
}
Server side :
<?php
$data["post"] = $_POST;
$email = $_POST["data"]["email"];
$password = $_POST["data"]["password"];
if(empty($email)) {
$errors['email'] = 'blank_email';
}
if(empty($password)) {
$errors['password'] = 'blank_password';
}
echo json_encode($data);
?>
Hi here you are returning null value from your method. Try this code. It will work.
private static JSONObject createJsonCredentials(String username, String password) {
JSONObject jsonOuter = new JSONObject();
try {
JSONObject jsonInner = new JSONObject();
jsonInner.put("email", "something#something.com");
jsonInner.put("password", "tralala");
jsonOuter.put("data", jsonInner);
} catch(JSONException ex) {
ex.printStackTrace();
}
return jsonOuter;
}

Android parse JSONObject

I've got a little problem with parsing json into my android app.
This is how my json file looks like:
{
"internalName": "jerry91",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
}
As You can see this structure is a little bit weird. I dont know how to read that data in my app. As I noticed those are all Objects not arrays :/
You can always use good old json.org lib. In your Java code :
First read your json file content into String;
Then parse it into JSONObject:
JSONObject myJson = new JSONObject(myJsonString);
// use myJson as needed, for example
String name = myJson.optString("name");
int profileIconId = myJson.optInt("profileIconId");
// etc
UPDATE 2018
After 5 years there is a new "standard" for parsing json on android. It's called moshi and one can consider it GSON 2.0. It's very similar but with design bugs fixed that are the first obstacles when you start using it.
https://github.com/square/moshi
First add it as a mvn dependency like this:
<dependency>
<groupId>com.squareup.moshi</groupId>
<artifactId>moshi-kotlin</artifactId>
<version>1.6.0</version>
</dependency>
After adding it we can use like so (taken from the examples):
String json = ...;
Moshi moshi = new Moshi.Builder().build();
JsonAdapter<BlackjackHand> jsonAdapter = moshi.adapter(BlackjackHand.class);
BlackjackHand blackjackHand = jsonAdapter.fromJson(json);
System.out.println(blackjackHand);
More infos on their GitHub page :)
[old]
I would recommend using Gson.
Here are some links for tutorials:
how to convert java objecto from json format using GSON
Parse JSON file using GSON
Simple GSON example
Converting JSON data to Java object
An alternative to Gson you could use Jackson.
Jackson in 5 minutes
how to convert java object to and from json
This libraries basically parse your JSON to a Java class you specified.
to know if string is JSONArray or JSONObject
JSONArray String is like this
[{
"internalName": "blaaa",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
},
{
"internalName": "blooo",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
}]
and this String as a JSONOject
{
"internalName": "domin91",
"dataVersion": 0,
"name": "Domin91",
"profileIconId": 578,
"revisionId": 0,
}
but how to call elements from JSONArray and JSONObject ?
JSNOObject info called like this
first fill object with data
JSONObject object = new JSONObject(
"{
\"internalName\": \"domin91\",
\"dataVersion\": 0,
\"name\": \"Domin91\",
\"profileIconId\": 578,
\"revisionId\": 0,
}"
);
now lets call information from object
String myusername = object.getString("internalName");
int dataVersion = object.getInt("dataVersion");
If you want to call information from JSONArray you must know what is the object position number or you have to loop JSONArray to get the information for example
looping array
for ( int i = 0; i < jsonarray.length() ; i++)
{
//this object inside array you can do whatever you want
JSONObject object = jsonarray.getJSONObject(i);
}
if i know the object position inside JSONArray ill call it like this
//0 mean first object inside array
JSONObject object = jsonarray.getJSONObject(0);
This part do in onBackground in AsyncTask
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
try {
result = json.getString("internalName");
data=json.getString("dataVersion");
ect..
} catch (JSONException e) {
e.printStackTrace();
}
JsonParser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
I suggest you to use a library like gson as #jmeier wrote on his answer. But if you want to handle json with android's defaults, you can use something like this:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String s = new String("{\"internalName\": \"domin91\",\"dataVersion\": 0,\"name\": \"Domin91\",\"profileIconId\": 578,\"revisionId\": 0,}");
try {
MyObject myObject = new MyObject(s);
Log.d("MY_LOG", myObject.toString());
} catch (JSONException e) {
Log.d("MY_LOG", "ERROR:" + e.getMessage());
}
}
private static class MyObject {
private String internalName;
private int dataVersion;
private String name;
private int profileIconId;
private int revisionId;
public MyObject(String jsonAsString) throws JSONException {
this(new JSONObject(jsonAsString));
}
public MyObject(JSONObject jsonObject) throws JSONException {
this.internalName = (String) jsonObject.get("internalName");
this.dataVersion = (Integer) jsonObject.get("dataVersion");
this.name = (String) jsonObject.get("name");
this.profileIconId = (Integer) jsonObject.get("profileIconId");
this.revisionId = (Integer) jsonObject.get("revisionId");
}
#Override
public String toString() {
return "internalName=" + internalName +
"dataVersion=" + dataVersion +
"name=" + name +
"profileIconId=" + profileIconId +
"revisionId=" + revisionId;
}
}
}
Please checkout ig-json parser or Logan Square for fast and light JSON library.
For comparison, this is the stats from Logan Square developer.
Here you can parse any file from assets folder
fetch file from assets folder
public void loadFromAssets(){
try {
InputStream is = getAssets().open("yourfile.json");
readJsonStream(is);
} catch (IOException e) {
e.printStackTrace();
}
}
Convert JSON to your class object
public void readJsonStream(InputStream in) throws IOException {
Gson gson = new Gson();
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
reader.setLenient(true);
int size = in.available();
Log.i("size", size + "");
reader.beginObject();
long starttime=System.currentTimeMillis();
while (reader.hasNext()) {
try {
Yourclass message = gson.fromJson(reader, Yourclass.class);
}
catch (Exception e){
Toast.makeText(this, e.getCause().toString(), Toast.LENGTH_SHORT).show();
}
}
reader.endObject();
long endtime=System.currentTimeMillis();
long diff=endtime-starttime;
int seconds= (int) (diff/1000);
Log.i("elapsed",seconds+"");
reader.close();
}

conversion from string to JSON object Android

I am working on an Android application. In my app I have to convert a string to JSON Object, then parse the values. I checked for a solution in Stackoverflow and found similar issue here link
The solution is like this
`{"phonetype":"N95","cat":"WP"}`
JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}");
I use the same way in my code . My string is
{"ApiInfo":{"description":"userDetails","status":"success"},"userDetails":{"Name":"somename","userName":"value"},"pendingPushDetails":[]}
string mystring= mystring.replace("\"", "\\\"");
And after replace I got the result as this
{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"Sarath Babu\",\"userName\":\"sarath.babu.sarath babu\",\"Token\":\"ZIhvXsZlKCNL6Xj9OPIOOz3FlGta9g\",\"userId\":\"118\"},\"pendingPushDetails\":[]}
when I execute JSONObject jsonObj = new JSONObject(mybizData);
I am getting the below JSON exception
org.json.JSONException: Expected literal value at character 1 of
Please help me to solve my issue.
Remove the slashes:
String json = {"phonetype":"N95","cat":"WP"};
try {
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
} catch (Throwable t) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
This method works
String json = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
try {
JSONObject obj = new JSONObject(json);
Log.d("My App", obj.toString());
Log.d("phonetype value ", obj.getString("phonetype"));
} catch (Throwable tx) {
Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}
try this:
String json = "{'phonetype':'N95','cat':'WP'}";
You just need the lines of code as below:
try {
String myjsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
JSONObject jsonObject = new JSONObject(myjsonString );
//displaying the JSONObject as a String
Log.d("JSONObject = ", jsonObject.toString());
//getting specific key values
Log.d("phonetype = ", jsonObject.getString("phonetype"));
Log.d("cat = ", jsonObject.getString("cat");
}catch (Exception ex) {
StringWriter stringWriter = new StringWriter();
ex.printStackTrace(new PrintWriter(stringWriter));
Log.e("exception ::: ", stringwriter.toString());
}
just try this ,
finally this works for me :
//delete backslashes ( \ ) :
data = data.replaceAll("[\\\\]{1}[\"]{1}","\"");
//delete first and last double quotation ( " ) :
data = data.substring(data.indexOf("{"),data.lastIndexOf("}")+1);
JSONObject json = new JSONObject(data);
To get a JSONObject or JSONArray from a String I've created this class:
public static class JSON {
public Object obj = null;
public boolean isJsonArray = false;
JSON(Object obj, boolean isJsonArray){
this.obj = obj;
this.isJsonArray = isJsonArray;
}
}
Here to get the JSON:
public static JSON fromStringToJSON(String jsonString){
boolean isJsonArray = false;
Object obj = null;
try {
JSONArray jsonArray = new JSONArray(jsonString);
Log.d("JSON", jsonArray.toString());
obj = jsonArray;
isJsonArray = true;
}
catch (Throwable t) {
Log.e("JSON", "Malformed JSON: \"" + jsonString + "\"");
}
if (object == null) {
try {
JSONObject jsonObject = new JSONObject(jsonString);
Log.d("JSON", jsonObject.toString());
obj = jsonObject;
isJsonArray = false;
} catch (Throwable t) {
Log.e("JSON", "Malformed JSON: \"" + jsonString + "\"");
}
}
return new JSON(obj, isJsonArray);
}
Example:
JSON json = fromStringToJSON("{\"message\":\"ciao\"}");
if (json.obj != null) {
// If the String is a JSON array
if (json.isJsonArray) {
JSONArray jsonArray = (JSONArray) json.obj;
}
// If it's a JSON object
else {
JSONObject jsonObject = (JSONObject) json.obj;
}
}
Using Kotlin
val data = "{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"somename\",\"userName\":\"value\"},\"pendingPushDetails\":[]}\n"
try {
val jsonObject = JSONObject(data)
val infoObj = jsonObject.getJSONObject("ApiInfo")
} catch (e: Exception) {
}
Here is the code, and you can decide which
(synchronized)StringBuffer or
faster StringBuilder to use.
Benchmark shows StringBuilder is Faster.
public class Main {
int times = 777;
long t;
{
StringBuffer sb = new StringBuffer();
t = System.currentTimeMillis();
for (int i = times; i --> 0 ;) {
sb.append("");
getJSONFromStringBuffer(String stringJSON);
}
System.out.println(System.currentTimeMillis() - t);
}
{
StringBuilder sb = new StringBuilder();
t = System.currentTimeMillis();
for (int i = times; i --> 0 ;) {
getJSONFromStringBUilder(String stringJSON);
sb.append("");
}
System.out.println(System.currentTimeMillis() - t);
}
private String getJSONFromStringBUilder(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("cat"))
.toString();
}
private String getJSONFromStringBuffer(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("phonetype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("cat"))
.toString();
}
}
May be below is better.
JSONObject jsonObject=null;
try {
jsonObject=new JSONObject();
jsonObject.put("phonetype","N95");
jsonObject.put("cat","wp");
String jsonStr=jsonObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}

Categories

Resources