This is the code I have been trying to parse using GSON, from an array of custom type.
class Message{
String username;
String text;
String user_pic;
public Message(String un, String msg){
username=un; text=msg;
}
}
Message[] messages = new Message[2];
messages[0]=new Message("rory","hi");
messages[1]=new Message("van","where's my money!");
String JSON2 = new Gson().toJson(messages, Message[].class);
returns "[null,null]"
ended up using:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
couldn't get GSON to work.
Try this to convert your custom array to Json string using Gson library.
String jsonString = new Gson().toJsonTree(messages).toString();
Refer Gson API documentation for more details. Hope this will be helpful.
Related
Using this https://www.thorntech.com/2016/03/parsing-json-android-using-volley-library/ to learn how to use Volley to access and parse object data from an api get route.
When I install the apk and start the app, the screen gives me no parsed object from this api get route (single user) https://reqres.in/api/users/2
Any idea why? I've never used volley before but I read all weekend about it and it's easy to understand and implement but clearly I'm doing something wrong with pointing to the data or the response object.
I appreciate any help to point me in the right direction.
package com.volleythorntech.example;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
// Will show the string "data" that holds the results
TextView results;
// URL of object to be parsed
String JsonURL = "https://reqres.in/api/users/2";
// This string will hold the results
String data = "";
// Defining the Volley request queue that handles the URL request concurrently
RequestQueue requestQueue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creates the Volley request queue
requestQueue = Volley.newRequestQueue(this);
// Casts results into the TextView found within the main layout XML with id jsonData
results = (TextView) findViewById(R.id.jsonData);
// Creating the JsonObjectRequest class called obreq, passing required parameters:
//GET is used to fetch data from the server, JsonURL is the URL to be fetched from.
JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, JsonURL,
// The third parameter Listener overrides the method onResponse() and passes
//JSONObject as a parameter
new Response.Listener<JSONObject>() {
// Takes the response from the JSON request
#Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = response.getJSONObject("data");
// Retrieves the string labeled "colorName" and "description" from
//the response JSON Object
//and converts them into javascript objects
String color = obj.getString("first_name");
String desc = obj.getString("last_name");
// Adds strings from object to the "data" string
data += "Color Name: " + color +
"nDescription : " + desc;
// Adds the data string to the TextView "results"
results.setText(data);
}
// Try and catch are included to handle any errors due to JSON
catch (JSONException e) {
// If an error occurs, this prints the error to the log
e.printStackTrace();
}
}
},
// The final parameter overrides the method onErrorResponse() and passes VolleyError
//as a parameter
new Response.ErrorListener() {
#Override
// Handles errors that occur due to Volley
public void onErrorResponse(VolleyError error) {
Log.e("Volley", "Error");
}
}
);
// Adds the JSON object request "obreq" to the request queue
requestQueue.add(obreq);
}
}
please check permission in your manifest
<uses-permission android:name="android.permission.INTERNET"/>
I am developing an Android app of my WooCommerce store and I'm getting store data like Products, Categories, Orders, Customers etc using GET http verb of WooCommerce REST Api. It's working fine and I'm able to generate oAuth 1.0 signature for api V2 and V3 properly. Now, I want to perform Write action. I learned from the same documentation that I need to use POST Http verb. I tried for the same and stuck.
When I'm performing any POST action with HttpGet or HttpPost request using URL, oAuth data and generated signature, I'm getting:
{"errors":[{"code":"woocommerce_api_authentication_error","message":"Invalid Signature - provided signature does not match"}]}
I'm following all the instructions given in document and found on Google as well, used "POST" string to generate oAuth signature, tried sending params using HttpGet and HttpPost but failed.
Can anyone please provide me some instruction or example to use POST Http verb for Android to perform write action using WooCommerce REST API. (like Create new Order, Create New Category etc)
I run into the same error and what I had to do was to create a different POST adapter class. I am using retrofit for network calls and here is my snippet code:
package me.gilo.a55thavenue.data;
import android.util.Base64;
import android.util.Log;
import com.squareup.okhttp.HttpUrl;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;
import retrofit.RxJavaCallAdapterFactory;
/**
* Created by Aron on 10/31/2015.
*/
public class PostRestAdapter {
static String oauth_nonce = "";
static String oauth_timestamp = "";
static String oauth_signature_method = "HMAC-SHA1";
static ArrayList<NameValuePair> params;
public static API createAPI(final String endpoint) {
setParams(endpoint);
// Define the interceptor, add authentication headers
Interceptor interceptor = new Interceptor() {
#Override
public Response intercept(Chain chain) throws IOException {
HttpUrl.Builder builder = chain.request().httpUrl().newBuilder();
for (NameValuePair entry : params) {
builder.addQueryParameter(entry.getName(), entry.getValue());
}
Request newRequest = chain.request()
.newBuilder()
.url(builder.build())
.build();
return chain.proceed(newRequest);
}
};
// Add the interceptor to OkHttpClient
OkHttpClient client = new OkHttpClient();
client.interceptors().add(interceptor);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API.BASE_URL)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
return retrofit.create(API.class);
}
public static ArrayList<NameValuePair> setParams(String endpoint) {
final String uri = API.BASE_URL + endpoint;
oauth_nonce = getOauth_nonce();
oauth_timestamp = getOauth_timestamp();
params = new ArrayList<>();
params.add(new BasicNameValuePair("oauth_consumer_key", API.CONSUMER_KEY));
params.add(new BasicNameValuePair("oauth_nonce", oauth_nonce));
params.add(new BasicNameValuePair("oauth_timestamp", oauth_timestamp));
params.add(new BasicNameValuePair("oauth_signature_method", oauth_signature_method));
Collections.sort(params, new SortParams());
String encodedParams = URLEncodedUtils.format(params, "utf-8");
Log.d("encodedParamString", encodedParams);
String string_to_sign = "";
try {
string_to_sign = (new StringBuilder("POST&")).append(URLEncoder.encode(uri, "utf-8")).append("&").append(URLEncoder.encode(encodedParams, "utf-8")).toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Log.d("string to sign", string_to_sign);
try {
Mac mac = Mac.getInstance("HMAC-SHA1");
String secret = API.CONSUMER_SECRET;
if (API.WP_API_VERSION.equals("3")) {
secret = API.CONSUMER_SECRET + "&";
}
mac.init(new SecretKeySpec(secret.getBytes("utf-8"), "HMAC-SHA1"));
String signature = Base64.encodeToString(mac.doFinal(string_to_sign.getBytes("utf-8")), 0).trim();
Log.d("signature", signature);
params.add(new BasicNameValuePair("oauth_signature", signature));
} catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
e.printStackTrace();
}
return params;
}
public static String getOauth_nonce() {
return (new StringBuilder(String.valueOf(Math.random() * 100000000D))).toString();
}
public static String getOauth_timestamp() {
long stamp = (long) (System.currentTimeMillis() / 1000D);
Log.d("stamp", stamp + "");
return (new StringBuilder(String.valueOf(stamp))).toString();
}
static class SortParams implements Comparator<NameValuePair> {
#Override
public int compare(NameValuePair nameValuePair1, NameValuePair nameValuePair2) {
return nameValuePair1.getName().compareTo(nameValuePair2.getName());
}
}
}
[Source: https://gist.github.com/Aroniez/41dbc5942f70641b397e]
I am new to android and stuck with some problem in Json parsing.
JSONArray resultJsonArray = data.getJSONArray("detailsArr");
getJSONArray is showing in red colour it means some issue is with getJSONArray. But I am not able to resolve it.
JSON:
{"msg":"","status":true,"result":[{"conversation":"<p>sani<\/p>","attachmentName":"","attachmentURL":"","clientType":"student","repliedOn":"30-Sep-15 11:19AM","expertName":"shubham goyal","expertPic":""},{"conversation":"<p>rere<\/p>","attachmentName":"","attachmentURL":"","clientType":"expert","repliedOn":"1-Oct-15 5:31PM","expertName":"shubham goyal","expertPic":""},{"conversation":"<p>all vl<\/p>","attachmentName":"","attachmentURL":"","clientType":"student","repliedOn":"1-Oct-15 5:44PM","expertName":"shubham goyal","expertPic":""},{"conversation":"<p>asa kk<\/p>","attachmentName":"","attachmentURL":"","clientType":"expert","repliedOn":"1-Oct-15 5:45PM","expertName":"shubham goyal","expertPic":""}]}
According to your JSON
it should be
JSONArray resultJsonArray = data.getJSONArray("result");
Since result is the name of the array.
I did't find detailsArr .
JSONObject reader = new JSONObject(Your_Json_Sring);
JSONArray jsonArray = reader.getJSONArray("result");
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject e = jsonArray.getJSONObject(i);
String conversation = e.getString("conversation");
}
Bundle doesn't have a method getJSONArray()
And your JSON string doesn't contain a key named detailsArr.
UPDATE:
I think what you want to do is this:
JSONArray resultJsonArray = new JSONObject(data.getString("detailsArr"))
.getJSONArray("result");
Try following things:
Check imports, it should be like (if you are using other library - should be similar)
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
Check if you data is type of JSONObject.
Step 1:
Using this Link Create one Pojo for your Json String.
Step 2:
put following in your gradle than sync your gradle file
compile 'com.google.code.gson:gson:2.4'
Step :3
and at Last Use following code for deserialized Json
Gson mGson = new Gson();
JsonReader reader = new JsonReader(new StringReader(YOUR_JSON_STRING));
final YOUR_POJO_CLASS_NAME mList = mGson.fromJson(reader, new TypeToken<YOUR_POJO_CLASS_NAME>() {
}.getType());
I hope your are clear with my solution.
Best of Luck
I have the following string:
{
"id":398225253590019,
"zip":"11375",
"street":"70-30 Austin St.",
"state":"NY",
"longitude":-73.845858172784,
"latitude":40.720457257566,
"country":"United States",
"city":"Forest Hills"
}
Please can anyone suggest me a convenient method for parsing it so that I can make a single object of the various components.
import org.json.JSONException;
import org.json.JSONObject;
...
...
String jsonstring = "{
"id":398225253590019,
"zip":"11375",
"street":"70-30 Austin St.",
"state":"NY",
"longitude":-73.845858172784,
"latitude":40.720457257566,
"country":"United States",
"city":"Forest Hills"
}";
JSONObject jObject = null;
try{
jObject = new JSONObject(jsonstring);
catch(JSONException e) {
//Json parse error usually
}
It is a JSON.
You can parset the String into JSONObject. Look the example of JSONTokenizer
That format is called json:
1.You can first create an object (Say "Object") with variables id,zip,country etc and getters and setters.
2.Download Link for jackson.
3.Import the library to your project.
Then just two lines of code:
ObjectMapper mapper = new ObjectMapper();
Object object = mapper.readValue(json, Object.class);
This Object class will contain the values...
Jackson Tutorial.
I'm trying to use GSON to parse some very simple JSON. Here's my code:
Gson gson = new Gson();
InputStreamReader reader = new InputStreamReader(getJsonData(url));
String key = gson.fromJson(reader, String.class);
Here's the JSON returned from the url:
{
"access_token": "abcdefgh"
}
I'm getting this exception:
E/AndroidRuntime(19447): com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 2
Any ideas? I'm new to GSON.
The JSON structure is an object with one element named "access_token" -- it's not just a simple string. It could be deserialized to a matching Java data structure, such as a Map, as follows.
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class GsonFoo
{
public static void main(String[] args)
{
String jsonInput = "{\"access_token\": \"abcdefgh\"}";
Map<String, String> map = new Gson().fromJson(jsonInput, new TypeToken<Map<String, String>>() {}.getType());
String key = map.get("access_token");
System.out.println(key);
}
}
Another common approach is to use a more specific Java data structure that matches the JSON. For example:
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
public class GsonFoo
{
public static void main(String[] args)
{
String jsonInput = "{\"access_token\": \"abcdefgh\"}";
Response response = new Gson().fromJson(jsonInput, Response.class);
System.out.println(response.key);
}
}
class Response
{
#SerializedName("access_token")
String key;
}
Another "low level" possibility using the Gson JsonParser:
package stackoverflow.questions.q11571412;
import com.google.gson.*;
public class GsonFooWithParser
{
public static void main(String[] args)
{
String jsonInput = "{\"access_token\": \"abcdefgh\"}";
JsonElement je = new JsonParser().parse(jsonInput);
String value = je.getAsJsonObject().get("access_token").getAsString();
System.out.println(value);
}
}
If one day you'll write a custom deserializer, JsonElement will be your best friend.
This is normal parsing exception occurred when Pojo key data type is different from json response
This is due to data type mismatch in Pojo class and actually data which comes in the Network api Response
Eg
data class ProcessResponse(
val outputParameters: String,
val pId: Int
)
got the same error due to api gives response as
{
"pId": 1",
"outputParameters": {
"": ""
}
}
Here POJO is outputParameters is String but as per api response its json