Unable to parse the id from moviedb api - json

Hi I'm trying to parse out the id's from an array. I have a logging method which shows a toast:
StringBuilder data= new StringBuilder();
JSONArray arrayMovies= response.getJSONArray(KEY_MOVIES);
for (int i = 0; i < arrayMovies.length(); i++) {
JSONObject currentMovie = arrayMovies.getJSONObject(i);
String id = currentMovie.getString(KEY_ID);
data.append(id+"\n");
}
L.t(getActivity(), data.toString());
.....
But It's not parsing it out. Just getting a list of the movies.
Here is the json file:
{
"page": 1,
"results": [
{
"adult": false,
"backdrop_path": "/tbhdm8UJAb4ViCTsulYFL3lxMCd.jpg",
"genre_ids": [
53,
28,
12
],
"id": 76341,
"original_language": "en",
"original_title": "Mad Max: Fury Road",
"overview": "An apocalyptic story set in the furthest reaches of our planet, in a stark desert landscape where humanity is broken, and most everyone is crazed fighting for the necessities of life. Within this world exist two rebels on the run who just might be"
}
]
}

Not sure, but maybe because id value has no quote, and therefore, can not be parsed as a String with getString() method

I think your code is OK, just need check the response and keys again, I have tested with hard-code the response as the String and 2 keys as the following:
String jsonString = "{\n" +
" \"page\": 1,\n" +
" \"results\": [\n" +
" {\n" +
" \"adult\": false,\n" +
" \"backdrop_path\": \"/tbhdm8UJAb4ViCTsulYFL3lxMCd.jpg\",\n" +
" \"genre_ids\": [\n" +
" 53,\n" +
" 28,\n" +
" 12\n" +
" ],\n" +
" \"id\": 76341,\n" +
" \"original_language\": \"en\",\n" +
" \"original_title\": \"Mad Max: Fury Road\",\n" +
" \"overview\": \"An apocalyptic story set in the furthest reaches of our planet, in a stark desert landscape where humanity is broken, and most everyone is crazed fighting for the necessities of life. Within this world exist two rebels on the run who just might be\"\n" +
" }\n" +
" ]\n" +
"}";
StringBuilder data= new StringBuilder();
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray arrayMovies= jsonObject.getJSONArray("results");
for (int i = 0; i < arrayMovies.length(); i++) {
JSONObject currentMovie = arrayMovies.getJSONObject(i);
String id = currentMovie.getString("id");
data.append(id+"\n");
}
Log.i("BNK", data.toString());
} catch (JSONException e) {
e.printStackTrace();
}
And here is the screenshot (please pay attention to logcat):

Related

I want to convert csv to json with key value pair

I have a JSON file as below and want to convert to json with Name key , value pair ,
Eg : "name":"emailAddress",
"value" :"Trest22#gmail.com"
If have multiple JSON tags then it should break into separate tag as shown in image.
Please help
[
{
"emailAddress": "Trest22#gmail.com",
"loginName": "Testinguser222",
"firstName": "Test222",
"surName": "Test22",
"primaryPhone": "",
"companyId": 123445,
"extracompanies": "[12311,33333]",
"middleName": "Test",
"mobilePhone": 6666666666,
"fax": 87687687686
}
]
Want to convert as below
{
{
"name":"emailAddress",
"value" :"Trest22#gmail.com"
}
{
"name":"loginName",
"value":"Testinguser222"
}
{
"name":"firstName",
"value":"Test222"
}
{
"name":"surName",
"value":"Test22"
}
{ "name":"extracompanies",
"value": "[12311,33333]"
}
I am not sure if any library can do that, however, in Java, you can achieve it as shown below,
ObjectMapper mapper = new ObjectMapper();
String test = "{\n" +
" \"emailAddress\": \"Trest22#gmail.com\",\n" +
" \"loginName\": \"Testinguser222\",\n" +
" \"firstName\": \"Test222\",\n" +
" \"surName\": \"Test22\",\n" +
" \"primaryPhone\": \"\",\n" +
" \"companyId\": 123445,\n" +
" \"extracompanies\": \"[12311,33333]\",\n" +
" \"middleName\": \"Test\",\n" +
" \"mobilePhone\": 6666666666,\n" +
" \"fax\": 87687687686\n" +
" \n" +
" }";
Map<String, Object> maps = mapper.readValue(test, Map.class);
List<Map<String,Object>> converted = maps.keySet().stream().map(key -> {
Map<String,Object> internalMap = new HashMap<>();
internalMap.put("name", key);
internalMap.put("value", maps.get(key));
return internalMap;
}).collect(Collectors.toList());
String json = mapper.writeValueAsString(converted);
Output
[{"name":"emailAddress","value":"Trest22#gmail.com"},{"name":"loginName","value":"Testinguser222"},{"name":"firstName","value":"Test222"},{"name":"surName","value":"Test22"},{"name":"primaryPhone","value":""},{"name":"companyId","value":123445},{"name":"extracompanies","value":"[12311,33333]"},{"name":"middleName","value":"Test"},{"name":"mobilePhone","value":6666666666},{"name":"fax","value":87687687686}]

Zuora payment-methods/credit-cards api returning 90000011 from java Client but returning success response from postman

I am in the middle of integration zuora apis with my application. These are the below 3 three apis I am using through following steps -
Step 1 Requesting for auth token
Service api (Test)- https://rest.apisandbox.zuora.com/oauth/token
Request Headers - Content-Type:application/x-www-form-urlencoded
Authorization:Basic YWYzNTg5ZWMtNTFmMC00YTc2LWFlZjEtYjk0YzZmYWE0Y2ViOlJDdGV5OGlTWFFUc00xQytTPTFYWD1POE9tRWM1c0FBWVBaaE5vV24=
Request Body - grant_type:client_credentials
Response Body - {
"access_token": "41947f41d664437a98a9da38a293c89d",
"token_type": "bearer",
"expires_in": 3598,
"scope": "entity.a083d63b-b3f5-8626-f793-65cec903f9ca platform.write service.events.read service.events.write service.genesis.read service.genesis.write service.notifications.read service.notifications.write service.usage.delete service.usage.update service.usage.write tenant.41231 user.2c92c094738e5b090173902066c201ba",
"jti": "41947f41d664437a98a9da38a293c89d"
}
Use access_token or jti value from auth token response and pass it on to the headers parameters as Authorization: Bearer
Step 2 : - Request for hmac-signatures for making payment
Service api (Test) - https://rest.apisandbox.zuora.com/v1/hmac-signatures
Request Headers - Content-Type:application/json
Authorization:Bearer 41947f41d664437a98a9da38a293c89d
Request Body - {
"accountKey": "A00000485",
"method": "POST",
"uri": "https://rest.apisandbox.zuora.com/v1/payment-methods/credit-cards"
}
Response Body - {
"signature": "MDgzN2ZkYjAzOTQ5NmQ5NDQyZjc5YTU3NjUwMDgxOGIxNTY3YWM2Mw==",
"token": "C41mzDTudB2uc0Jc6vwrhQGvwq3JTxsF",
"success": true
}
The signature needs to be added in Make Payment header asSignature:MDgzN2ZkYjAzOTQ5NmQ5NDQyZjc5YTU3NjUwMDgxOGIxNTY3YWM2Mw==
The token needs to be added in Make Payment header as Token:C41mzDTudB2uc0Jc6vwrhQGvwq3JTxsF
Step 3:- Make payment request –
Service Api - https://apisandbox-api.zuora.com/rest/v1/payment-methods/credit-cards
Headers Parameters –
Host:apisandbox-api.zuora.com
Signature:MDgzN2ZkYjAzOTQ5NmQ5NDQyZjc5YTU3NjUwMDgxOGIxNTY3YWM2Mw==
Token:C41mzDTudB2uc0Jc6vwrhQGvwq3JTxsF
Content-Type:application/json
Origin:www.test.gov.uk
Cache-Control:no-cache
Request Parameters – {
"defaultPaymentMethod": true,
"cardHolderInfo":
{"addressLine1": "77 Fallon Glen",
"addressLine2": "",
"zipCode": "94020",
"state": "California",
"phone": "4155551234",
"country": "USA",
"cardHolderName": "Bill Thiebault",
"city": "Fremont",
"email": "bill#testaddress.com"},
"expirationMonth": "10",
"accountKey": "A00000485",
"creditCardType": "Visa",
"expirationYear": "2021",
"creditCardNumber": "4012888888881121",
"securityCode": "123"
}
Response Body – {
"success": true,
"**paymentMethodId": "2c92c0fb73ad855c0173b8c3316b36a1"**
}
When I use the same steps using postman I am able to get a success response. And the Payment Method id is also getting generated. Using java client the first two services are being executed. But the issue appears when I hit the request for Payment-Method / credit cards,
It always returns -
{
"success" : false,
"processId" : "84AD9CF25EC6623A",
"reasons" : [ {
"code" : 90000011,
"message" : "this resource is protected, please sign in first"
} ]
}
Please suggest me if I missed anything here.
I missed to set the header value. Here I am posting the method that I used -
It consists Oauth token generation -> generation hmac signature -> making request for payment-method / credit card. It worked for me.
public void testSpringZuorPaymentCreditCardDifferent() {
HTTPHelper httpHelper = null;
String urlOAuthToken = "https://rest.apisandbox.zuora.com/oauth/token";
String resp = null;
try {
String userNameAndPassword ="c59b646b-53c6-45fb-b9c3-d3ea0978033d" + ":" +"6VLNxA=Fbaorb7yqXO3YRaiS2a+WUfLtwOiVugLqQ";
String authorizationHeaderValue = "Basic " + new String(Base64.encode(userNameAndPassword.getBytes()));
httpHelper = new HTTPHelper(new URL(urlOAuthToken));
Map<String, String> hdmp = new HashMap<String, String>();
hdmp.put("Authorization", authorizationHeaderValue);
hdmp.put("Content-Type", "application/x-www-form-urlencoded");
httpHelper.setHeaders(hdmp);
String req = "grant_type=client_credentials";
System.out.println("REQUEST: " + req);
resp = httpHelper.post(req, 60000, 60000);
System.out.println("OAuth token response : " + resp);
}catch(Exception e) {
e.printStackTrace();
}
String[] arrOfStr = resp.split("\\W+");
System.out.println("Bearer token---------" + arrOfStr[2]);
String urlHmacSignatureUrl = "https://rest.apisandbox.zuora.com/v1/hmac-signatures";
try {
httpHelper = new HTTPHelper(new URL(urlHmacSignatureUrl));
Map<String, String> hdmp = new HashMap<String, String>();
hdmp.put("Authorization", "Bearer " + new String(Base64.encode(arrOfStr[2].getBytes())));
hdmp.put("Content-Type", "application/json");
hdmp.put("cache-control", "no-cache");
httpHelper.setHeaders(hdmp);
String req = "{\n \"accountKey\": \"A00000194\", \n \"method\": \"POST\", \n \"uri\": \"https://rest.apisandbox.zuora.com/v1/payment-methods/credit-cards\"\n}";
System.out.println("REQUEST: " + req);
resp = httpHelper.post(req, 60000, 60000);
System.out.println("Hmac Signature response : " + resp);
}catch(Exception e) {
e.printStackTrace();
}
arrOfStr = resp.split("\\W+");
System.out.println("signature : - "+arrOfStr[2]);
System.out.println("token : - "+arrOfStr[4]);
String serverURI = "https://apisandbox-api.zuora.com/rest/v1/payment-methods/credit-cards";
try {
java.util.Map<String, String> headers = new java.util.HashMap<String, String>();
httpHelper = new HTTPHelper(new URL(serverURI));
headers.put("Content-Type", "application/json");
// headers.put("Signature", arrOfStr[2]+"==");
headers.put("Signature", new String(Base64.encode("YjM4MDY5MDliZmVkYmZiOGFkNmQ1YzFhYzFmNzMyOGI3NjExM2JlNQ==".getBytes())));
headers.put("Token", new String(Base64.encode(arrOfStr[4].getBytes())));
httpHelper.setHeaders(headers);
String req = "{\r\n" +
" \"defaultPaymentMethod\":true,\r\n" +
" \"cardHolderInfo\":{\r\n" +
" \"addressLine1\":\"77 Fallon Glen\",\r\n" +
" \"addressLine2\":\"\",\r\n" +
" \"zipCode\":\"94020\",\r\n" +
" \"state\":\"California\",\r\n" +
" \"phone\":\"4155551234\",\r\n" +
" \"country\":\"USA\",\r\n" +
" \"cardHolderName\":\"Bill Thiebault\",\r\n" +
" \"city\":\"Fremont\",\r\n" +
" \"email\":\"bill#testaddress.com\"\r\n" +
" },\r\n" +
" \"expirationMonth\":\"10\",\r\n" +
" \"accountKey\":\"A00000485\",\r\n" +
" \"creditCardType\":\"Visa\",\r\n" +
" \"expirationYear\":\"2021\",\r\n" +
" \"creditCardNumber\":\"4012888888881121\",\r\n" +
" \"securityCode\":\"123\"\r\n" +
"}";
System.out.println("Req: " + req);
resp = httpHelper.post(req, 60000, 60000);
System.out.println("Payment Method - Credit Cards: " + resp);
}catch(Exception e) {
e.printStackTrace();
}
}

Extract some value without key from a json object

I am using java to extract a list of node ids from an elastic search running tasks response.
The response looks like this
{
"nodes": {
"ZKUuxQZpRCCcJ0njBM1P0A": {
"name": "ZKUuxQZ",
"transport_address": "127.0.0.1:9300",
"host": "127.0.0.1",
"ip": "127.0.0.1:9300",
"roles": [
"master",
"data",
"ingest"
],
"tasks": {
"ZKUuxQZpRCCcJ0njBM1P0A:118": {
"node": "ZKUuxQZpRCCcJ0njBM1P0A",
"id": 118,
"type": "transport",
"action": "indices:data/write/delete/byquery",
"start_time_in_millis": 1527808643421,
"running_time_in_nanos": 154234724059,
"cancellable": true,
"headers": {}
}
}
}
}
}
In this example, I want to exact ZKUuxQZpRCCcJ0njBM1P0A:118. Can someone give me an example how to extract this information?
Option 1, java json parser. I wanted to write a response class and parse the json string, but ZKUuxQZpRCCcJ0njBM1P0A:118 is not in the key:value format. I am not sure how to extract it.
Option 2, using regex. The node id part may also have - or _. Can someone provide a neat java regex solution? So far my regex is [a-zA-Z0-9\-\_]+\:[0-9]+, I am not sure if this is safe enough.
Thanks.
One way you can do this is by using org.json library and create JSONObject and using keys() you can get all the keys and use this to achieve your task
Add the following dependency in your pom.xml
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20180130</version>
</dependency>
Then you can do something like below:
String jsonString = "{\n" +
" \"nodes\": {\n" +
" \"ZKUuxQZpRCCcJ0njBM1P0A\": {\n" +
" \"name\": \"ZKUuxQZ\",\n" +
" \"transport_address\": \"127.0.0.1:9300\",\n" +
" \"host\": \"127.0.0.1\",\n" +
" \"ip\": \"127.0.0.1:9300\",\n" +
" \"roles\": [\n" +
" \"master\",\n" +
" \"data\",\n" +
" \"ingest\"\n" +
" ],\n" +
" \"tasks\": {\n" +
" \"ZKUuxQZpRCCcJ0njBM1P0A:118\": {\n" +
" \"node\": \"ZKUuxQZpRCCcJ0njBM1P0A\",\n" +
" \"id\": 118,\n" +
" \"type\": \"transport\",\n" +
" \"action\": \"indices:data/write/delete/byquery\",\n" +
" \"start_time_in_millis\": 1527808643421,\n" +
" \"running_time_in_nanos\": 154234724059,\n" +
" \"cancellable\": true,\n" +
" \"headers\": {}\n" +
" }\n" +
" }\n" +
" }\n" +
" }\n" +
"}";
JSONObject jsonObject = new JSONObject(jsonString);
Set<String> topLevelKeys = jsonObject.keySet();
for (String key : topLevelKeys) {
Object value = jsonObject.get(key);
if (value instanceof JSONObject) {
JSONObject valueObject = jsonObject.getJSONObject(key);
System.out.println(valueObject.toString());
}
}
Extend this as per your requirement.
So regex is too hacky and I figured it out using gson. I wish ElasticSearch can offer us some standard library to extract all kinds of responses. Here is my solution using gson.
import com.google.gson.*;
import org.json.JSONObject;
public class test {
public static void main(String[] args) throws Exception {
String jsonString = "json_format elasticsearch reponse for listing running tasks"
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(content).getAsJsonObject();
jsonObject.getAsJsonObject("nodes").entrySet().forEach(
s -> {
s.getValue().getAsJsonObject().getAsJsonObject("tasks").entrySet().forEach( s2 -> {
System.out.println(s2.getKey());
});
});
}
It prints all the running task ids like the following. It's technically nodeId:taskId, but ES has a very vague description in their task API docs(It says you can use TASK_ID to check a status of a task, well that TASK_ID is nodeId:taskId).
Mw-3i39gTHGxu5c8z9viQQ:503209021
DZ29LMsWR0aW9guWZTYe2Q:482931604
6CAbDZSWR8SfwZgnRT0qNg:494351185
Use the following regex:
[a-zA-Z0-9-_]*[0-9]+[a-zA-Z]+:[0-9]*
You can find the test result here:
https://regexr.com/3qdug

How to convert jCard into first-class JSON?

I need a stable and secure convertion algorithm (any language), that can produce the final output as "first class" JSON objects. Example:
jCard format: [["version", {}, "text", "4.0"],["fn", {}, "text", "Forrest Gump"]]
First-class JSON format: {"version":"4.0","fn":"Forrest Gump"}.
In python
first, I create one function named jcard_to_json that takes a jCard as input and converts it to a "first-class" JSON object. The function iterates over the items in the jCard, and for each item, it adds a key-value pair to the json_obj dictionary, where the key is the first item in the jCard thing and the value is the fourth item
Example:-
def jcard_to_json(jcard):
json_obj = {}
for item in jcard:
json_obj[item[0]] = item[3]
return json_obj
jcard = [["version", {}, "text", "4.0"], ["fn", {}, "text", "Forrest
Gump"]]
json_obj = jcard_to_json(jcard)
In Java.
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JCardTest {
public static void main(String[] args) throws JSONException {
String jcardStr = "[\"vcard\","
+ " ["
+ " [\"version\", {}, \"float\", \"4.0\"],"
+ " [\"fn\", {}, \"text\", \"John Doe\"],"
+ " [\"gender\", {}, \"text\", \"M\"],"
+ " [\"categories\", {}, \"text\", \"computers\", \"cameras\"],"
+ " [\"number\", {}, \"integer\", 12345],"
+ " [\"adr\","
+ " { \"type\": \"work\" },"
+ " \"text\","
+ " ["
+ " \"\","
+ " \"Suite D2-630\","
+ " \"2875 Laurier\","
+ " \"Quebec\","
+ " \"QC\","
+ " \"G1V 2M2\","
+ " \"Canada\""
+ " ]"
+ " ]"
+ " ]"
+ " ]";
JSONArray jcard = new JSONArray(jcardStr);
jcard = jcard.getJSONArray(1);
JSONObject result = new JSONObject();
for (int i = 0; i < jcard.length(); i++) {
JSONArray arr = jcard.getJSONArray(i);
String name = arr.getString(0);
String dataType = arr.getString(2);
if (arr.length() == 4) {
switch (dataType) {
case "integer": {
long val = arr.getLong(3);
result.put(name, val);
}
break;
case "float": {
double val = arr.getDouble(3);
result.put(name, val);
}
break;
default:
Object val = arr.get(3);
if (val instanceof JSONArray) {
result.put(name, (JSONArray) val);
} else {
result.put(name, val.toString());
}
break;
}
} else {
JSONArray resArr = new JSONArray();
for (int j = 3; j < arr.length(); j++) {
resArr.put(arr.get(j).toString());
}
result.put(name, resArr);
}
}
System.out.println(result);
}
}
This ignores the 'parameter" part (arr.get(1)) of the jCard entries.
the code is verbose to not to hide important details. it could be written more compact.
Example is based on examples in the jCard RFC7095.

Deserialize json into complex Map object using jackson

Consider the following json example
{
"key1" : {
"k11":["vala","valb","valc"],
"k12":["vald"],
"k13":["vale","valf"]
},
"key2" : {
"key21":["valg","valh","vali"],
"key22":["valj"],
"key23":["valk","vall"]
}
}
This translates into a Map<String,Map<String,List<String>>>.
Could anyone please let me know how i can convert this in this into this complex Map object. I do a a method called constructMapType, but not sure if it handles complex Map type.
Seems to work fine with .constructMapType(Map.class, String.class, Map.class)
public static void main(String[] args) throws Exception {
final String json
= "{\n"
+ " \"key1\" : {\n"
+ " \"k11\":[\"vala\",\"valb\",\"valc\"],\n"
+ " \"k12\":[\"vald\"],\n"
+ " \"k13\":[\"vale\",\"valf\"]\n"
+ " },\n"
+ " \"key2\" : {\n"
+ " \"key21\":[\"valg\",\"valh\",\"vali\"],\n"
+ " \"key22\":[\"valj\"],\n"
+ " \"key23\":[\"valk\",\"vall\"]\n"
+ " }\n"
+ "}";
ObjectMapper mapper = new ObjectMapper();
Map<String, Map<String, List<String>>> map
= mapper.readValue(json,TypeFactory.defaultInstance()
.constructMapType(Map.class, String.class, Map.class));
for (String outerKey: map.keySet()) {
System.out.println(outerKey + ": " + map.get(outerKey));
for (String innerKey: map.get(outerKey).keySet()) {
System.out.print(innerKey + ": [");
for (String listValue: map.get(outerKey).get(innerKey)) {
System.out.print(listValue + ",");
}
System.out.println("]");
}
}
}
You could go all the way down listing all the generics down to the List<String>, but as seen above it isn't necessary. But just to show what I mean
TypeFactory factory = TypeFactory.defaultInstance();
Map<String, Map<String, List<String>>> map
= mapper.readValue(json, factory.constructMapType(
Map.class,
factory.constructType(String.class),
factory.constructMapType(
Map.class,
factory.constructType(String.class),
factory.constructCollectionType(
List.class,
String.class))));