Unable to List Item via EBay's Inventory API - java

I'm attempting to list an item on EBay using EBay's Inventory API via the following code (I'm using Apache HTTP Client):
public void put() throws ClientProtocolException, IOException
{
String url = "https://api.ebay.com/sell/inventory/v1/inventory_item/83368339";
String charset = "utf-8";
HttpClient client = HttpClientBuilder.create().build();
HttpPut put = new HttpPut(url);
// add request header
put.addHeader("Authorization", "Bearer <TOKEN>");
put.addHeader("Content-Language", "en-US");
String json = "{ \"availability\": { \"pickupAtLocationAvailability\": [ { \"availabilityType\": \"IN_STOCK\", \"fulfillmentTime\": { \"unit\": \"TimeDurationUnitEnum\": \"BUSINESS_DAY\", \"value\": 1 }, \"merchantLocationKey\": \"NJ\", \"quantity\": 1 } ], \"shipToLocationAvailability\": { \"quantity\": 1 } }, \"condition\": \"ConditionEnum : [NEW]\", \"conditionDescription\": \"New condition\","
+ "\"product\": { \"aspects\": \"object\", \"brand\": \"Outlite\", \"description\": \"ADJUSTABLE FOCUS: Intense Spotlight for long range observation can up to 600 feet, Circle Floodlight for large area illumination\", \"imageUrls\": [ \"https://images-na.ssl-images-amazon.com/images/I/71c57aJiDAL._SL1500_.jpg\" ], \"title\": \"Outlite A100 Portable Ultra Bright Handheld LED Flashlight\", \"sku\": \"sku546372817\" }";
HttpResponse response = client.execute(put);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result);
}
However I'm encountering the following error:
Response Code : 400
{"errors":[{"errorId":2004,"domain":"ACCESS","category":"REQUEST","message":"Invalid request","longMessage":"The request has errors. For help, see the documentation for this API.","parameters":[{"name":"reason","value":"Could not serialize field [availability.pickupAtLocationAvailability.availabilityType]"}]}]}

From the comments above, there were a few issues:
Remove the surrounding parentheses
Remove the surrounding quotes around the JSON
Enum formatting
After the last comment and confirming that removing the square brackets might have cleared up the availabilityType enum issue, here's what I think your final JSON should look like:
String json = "{ \"availability\": { \"pickupAtLocationAvailability\": [ { \"availabilityType\": \"IN_STOCK\", \"fulfillmentTime\": { \"unit\": \"BUSINESS_DAY\", \"value\": 1 }, \"merchantLocationKey\": \"NJ\", \"quantity\": 1 } ], \"shipToLocationAvailability\": { \"quantity\": 1 } }, \"condition\": \"NEW\", \"conditionDescription\": \"New condition\","
+ "\"product\": { \"aspects\": \"object\", \"brand\": \"Outlite\", \"description\": \"ADJUSTABLE FOCUS: Intense Spotlight for long range observation can up to 600 feet, Circle Floodlight for large area illumination\", \"imageUrls\": [ \"https://images-na.ssl-images-amazon.com/images/I/71c57aJiDAL._SL1500_.jpg\" ], \"title\": \"Outlite A100 Portable Ultra Bright Handheld LED Flashlight\", \"sku\": \"sku546372817\" }}";
Here it is split out into non-Java escapedness:
{
"availability": {
"pickupAtLocationAvailability": [{
"availabilityType": "IN_STOCK",
"fulfillmentTime": {
"unit": "BUSINESS_DAY",
"value": 1
},
"merchantLocationKey": "NJ",
"quantity": 1
}],
"shipToLocationAvailability": {
"quantity": 1
}
},
"condition": "NEW",
"conditionDescription": "New condition",
"product": {
"aspects": "object",
"brand": "Outlite",
"description": "ADJUSTABLE FOCUS: Intense Spotlight for long range observation can up to 600 feet, Circle Floodlight for large area illumination",
"imageUrls": ["https://images-na.ssl-images-amazon.com/images/I/71c57aJiDAL._SL1500_.jpg"],
"title": "Outlite A100 Portable Ultra Bright Handheld LED Flashlight",
"sku": "sku546372817"
}
}
I modified the fulfillmentTime.unit and condition enums as well. It also looks like you might've been missing an a closing curly bracket at the end, so I added that as well.

Related

Request multiple elements from Adobe's SiteCatalyst using Java

Here's my Java code in order to extract data from Adobe Analytics: (cloned from GitHub repository)
public static AnalyticsClient SecretAuthentication(String endpoint,String username,String password){
AnalyticsClient client = new AnalyticsClientBuilder()
.setEndpoint(endpoint)
.authenticateWithSecret(username, password)
.build();
return client;
}
public static void main(String[] args) throws IOException, InterruptedException{
AnalyticsClient client = SecretAuthentication("api.omniture.com","username","my_secret_pass");
ReportDescription desc = new ReportDescription();
String rsid="my_rs_id";
desc.setReportSuiteID(rsid);
desc.setDateFrom("2016-10-12"); // YYYY-MM-DD
desc.setDateTo("2016-10-13");
desc.setMetricIds("entries","orders","pageviews","visits","visitors");
String[] elements = new String[2];
elements[0]="prop3";
elements[1]="prop33";
desc.setElementIds(elements);
//Pass the description to the API queue method, which will start the process of preparing the report:
ReportMethods reportMethods = new ReportMethods(client);
int reportId = reportMethods.queue(desc);
System.out.println(reportId);
//The received integer is a report id, which can be used to receive the actual report using the get() method.
//Preparing report takes some time, and the get() method will throw an exception with appropriate message if the report is not ready yet.
//Following code runs the get() method in a loop, waiting until the report is ready:
ReportResponse response = null;
while (response == null) {
try {
response = reportMethods.get(reportId);
//System.out.println(response.toString());
} catch (ApiException e) {
System.out.println(e.toString());
Thread.sleep(3000);
continue;
}
}
List<ReportData> responseData = response.getReport().getData();
System.out.println("Is there data in the report? "+responseData.size());
for (int j = 0; j < responseData.size(); j++)
{
System.out.println(responseData.get(j).getName()+ " has :");
System.out.println(responseData.get(j).getCounts());
}
}
An example output of the last "for" statement is:
FR has :
[35732.0, 0.0, 115146.0, 36402.0, 32111.0]
The 5-sized vector includes the metric values ("entries","orders","pageviews","visits","visitors")
The "FR" (France) is the value of the first element (prop3) which is actually the "Country" variable.
The problem is that I have no information about the second element, prop33 (prop33 is "Device Type").
String[] elements = new String[2];
elements[0]="prop3";
elements[1]="prop33";
The most important is that Adobe seems to ignore the second element (prop33) and considers only the first one (prop3) for its search. I can prove this by changing the order of the two elements in elements array.
String[] elements = new String[2];
elements[0]="prop33";
elements[1]="prop3";
If I place prop33 first the output lines are different and Adobe responds as if prop33(Device Type) were the only criterion. For example:
iPhone has :
[47636.0, 6.0, 107440.0, 47729.0, 42330.0]
So, how can I send two or more elements as a matching criterion??
I figured it out. The "problem" has nothing to do with the parameter format!! The Adobe response follows the json format too. In order to see all response data you need to call the "getBreakdown()" method in order to discover the "lower" layers of the json response tree! In my attached code the "for" statement prints only data for the prop3 json element because this is the first layer of Adobe's response. If someone wants to see prop33 element should do the following:
for (int j = 0; j < responseData.size(); j++)
{
System.out.println(responseData.get(j).getName()+ " has :");
System.out.println(responseData.get(j).getCounts());
List<ReportData>reportData;
reportData = responseData.get(j).getBreakdown();//<---Here's what is needed!!
for (int i = 0; i < reportData.size(); i++)
{
System.out.println(" "+reportData.get(i).getName());
System.out.println(" "+reportData.get(i).getCounts());
}
System.out.println("===============================================");
}
In general you need one of the many and handy json reader java libraries to traverse the json tree!!
This isn't an answer more of a response to your last comment that's too long for a comment that should hopefully help you figure out what the problem is. Again disclaimer that I'm not an actual java coder so take that for what it's worth. But..
Firstly, just to be clear, you did try this, right?
desc.setElementIds("prop3", "prop33");
And you say that doesn't work? Because looking at setElementIds I see
public void setElementIds(String... elementIds) { .. }
My 5 minute understanding of java is String... is basically syntactic sugar for String[] (array) but it's to accept the strings as multiple arguments passed, not a single array of strings, so it looks to me that passing multiple args is indeed the way to go.
But overall you should check what is actually being sent to Adobe in the request. I expect the requirements are similar for the soap/xml version, but I don't know really know the soap/xml version so here's the JSON version. Based on what you posted (Report.Queue) JSON object payload hould look like this:
{
"reportDescription":{
"reportSuiteID":"my_rs_id",
"dateFrom":"2016-10-12",
"dateTo":"2016-10-13",
"metrics":[
{
"id":"entries"
},
{
"id":"orders"
},
{
"id":"pageviews"
},
{
"id":"visits"
},
{
"id":"visitors"
}
],
"elements":[
{
"id":"prop3"
},
{
"id":"prop33"
}
]
}
}
So check the http(s) request to make sure it looks like that (or soap/xml equiv).
And your (JSON) response (Report.Get) should look something like this:
{
"report":{
"type":"ranked",
"elements":[
{
"id":"prop3",
"name":"prop3 name here"
},
{
"id":"prop33",
"name":"prop33 name here"
}
],
"reportSuite":{
"id":"my_rs_id",
"name":"rsid name here"
},
"period":"Wed. 12 Oct. 2016 - Thu. 13 Oct. 2016",
"metrics":[
{
"id":"entries",
"name":"Entries",
"type":"number",
"decimals":0,
"latency":4599,
"current":false
},
{
"id":"orders",
"name":"Orders",
"type":"number",
"decimals":0,
"latency":4599,
"current":false
},
{
"id":"pageviews",
"name":"Page Views",
"type":"number",
"decimals":0,
"latency":4599,
"current":false
},
{
"id":"visits",
"name":"Visits",
"type":"number",
"decimals":0,
"latency":4599,
"current":false
},
{
"id":"visitors",
"name":"Visitors",
"type":"number",
"decimals":0,
"latency":4599,
"current":false
}
],
"data":[
{
"name":"<first prop3 value>",
"url":"",
"counts":[
"246944",
"0",
"494509",
"251168",
"200670"
],
"breakdown":[
{
"name":"<first breakdown prop33 value>",
"url":"",
"counts":[
"226556",
"0",
"460021",
"231637",
"184294"
]
},
{
"name":"<second breakdown prop33 value>",
"url":"",
"counts":[
"17058",
"0",
"23930",
"17628",
"15085"
]
} //, etc...
]
},
{
"name":"<second prop3 value>",
"url":"",
"counts":[
"246944",
"0",
"494509",
"251168",
"200670"
],
"breakdown":[
{
"name":"<first breakdown prop33 value>",
"url":"",
"counts":[
"226556",
"0",
"460021",
"231637",
"184294"
]
},
{
"name":"<second breakdown prop33 value>",
"url":"",
"counts":[
"17058",
"0",
"23930",
"17628",
"15085"
]
} //, etc...
]
} //,etc..
],
"totals":[
"253490",
"0",
"503495",
"253490",
"201190"
],
"version":"1.4.16.10"
},
"waitSeconds":0,
"runSeconds":0
}

Formatting Json Code in Java

I need to convert the following Json code into Java.
{
"service": {
"type": "nyd",
"discount": 0.20,
"items": [
{
"asin": "....",
"link": "http://amazon.com/.....",
"quantity": 2
},
// ...
],
// See /addresses
"shipping_address": {
"full_name": "Mr Smith",
"street1": "Some Mission St",
"street2": "", // Optional
"city": "San Francisco",
"state": "CA",
"zip": "94000",
"country": "US",
"phone": "1234567890"
}
}
}
I'm currently implementing this by using the following code:
String postUrl = "https://API.example.com";
Gson gson = new Gson();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPostRequest = new HttpPost(postUrl);
StringEntity postingString = new StringEntity("{\"service\" : {\"type\":\"nnn\", \"discount\":" + 0.2 + ",\"items\" : [ { \"asin\":\"B018Y1XXT6\", \"link\":\"https://www.amazon.com/Yubico-Y-159-YubiKey-4-Nano/dp/B018Y1XXT6/\", \"quantity\":" + 1 + " } ], \"shipping_address\" : {\"full_name\":\"Steven Smith\", \"street1\":\"11 Man Rd\", \"street2\":\"\", \"city\":\"Woonsocket\", \"state\":\"RI\", \"zip\":\"02844\", \"country\":\"US\", \"phone\":\"7746536483\" } } } ");
Mote: the values are different but I'm trying to achieve the same syntax.
System.out.println("Post String value: " + IOUtils.toString(postingString.getContent()));
httpPostRequest.addHeader("Authorization", "Token " + apiKey);
httpPostRequest.setEntity(postingString);
httpPostRequest.setHeader("Content-type", "application/json");
//httpPostRequest.addHeader("content-type", "application/x-www-form-urlencoded");
HttpResponse response = httpClient.execute(httpPostRequest);
System.out.println(response.toString());
The "postString" value is:
{"service" : {"type":"nnn", "discount":0.2,"items" : [ { "asin":"B018Y1XXT6", "link":"https://www.amazon.com/Yubico-Y-159-YubiKey-4-Nano/dp/B018Y1XXT6/", "quantity":1 } ], "shipping_address" : {"full_name":"Steven Smith", "street1":"11 Man Rd", "street2":"", "city":"Woonsocket", "state":"RI", "zip":"02844", "country":"US", "phone":"17746536483" } } }
However, when I attempt to submit the request I get a Bad Request error.
How can I format the String correctly?
Thanks
You have sent an incorrect json String if you want to go with the json provided .Following are the errors:
1) "service = {\"type\" should be {\"service\" : {\"type
2) discount should not be a string
\"discount\":\"0.2\", should be \"discount\":" + 0.2 + ",
3) items = [ should be \"items\" : [
4) quantity should not be string
\"quantity\":\"1\" } should be \"quantity\":" + 1 + "}
5) comma missing before shipping address key
] shipping_address = should be ], \"shipping_address\" :
6) add one more } at the end

Expected BEGIN_OBJECT but was STRING - json without key

I'm generally a beginner in Android and json, and I'm stuck on one part and need some help. I'm trying to use Rotten Tomatoes json. I managed read almost everything, except the part where there isn't key in json. Here is the json:
{
"movies": [{
"id": "771359313",
"title": "Dumb and Dumber To",
"year": 2014,
"mpaa_rating": "PG-13",
"runtime": 109,
"critics_consensus": "",
"release_dates": {
"theater": "2014-11-14"
},
"ratings": {
"critics_rating": "Rotten",
"critics_score": 25,
"audience_rating": "Spilled",
"audience_score": 54
},
"synopsis": "Jim Carrey and Jeff Daniels reprise their signature roles as Lloyd and Harry in the sequel to the smash hit that took the physical comedy and kicked it in the nuts: Dumb and Dumber To. The original film's directors, Peter and Bobby Farrelly, take Lloyd and Harry on a road trip to find a child Harry never knew he had and the responsibility neither should ever, ever be given. The Farrelly brothers produce Dumb and Dumber To alongside Riza Aziz and Joey McFarland of Red Granite Pictures. They are joined by fellow producers Charles B. Wessler and Bradley Thomas. Universal Pictures will distribute the film in the United States, Canada and select international territories.(C) Universal",
"posters": {
"thumbnail": "http://content6.flixster.com/movie/11/17/88/11178864_tmb.jpg",
"profile": "http://content6.flixster.com/movie/11/17/88/11178864_tmb.jpg",
"detailed": "http://content6.flixster.com/movie/11/17/88/11178864_tmb.jpg",
"original": "http://content6.flixster.com/movie/11/17/88/11178864_tmb.jpg"
},
"abridged_cast": [{
"name": "Jim Carrey",
"id": "162659418",
"characters": ["Lloyd Christmas"]
}, {
"name": "Jeff Daniels",
"id": "162654392",
"characters": ["Harry Dunne"]
}, {
"name": "Kathleen Turner",
"id": "162658757",
"characters": ["Fraida Felcher"]
}, {
"name": "Rob Riggle",
"id": "770750133",
"characters": ["Travis/Captain Lippincott"]
}, {
"name": "Jennifer Lawrence",
"id": "770800260",
"characters": ["Young Fraida Felcher"]
}],
"alternate_ids": {
"imdb": "2096672"
},
"links": {
"self": "http://api.rottentomatoes.com/api/public/v1.0/movies/771359313.json",
"alternate": "http://www.rottentomatoes.com/m/dumb_and_dumber_to/",
"cast": "http://api.rottentomatoes.com/api/public/v1.0/movies/771359313/cast.json",
"reviews": "http://api.rottentomatoes.com/api/public/v1.0/movies/771359313/reviews.json",
"similar": "http://api.rottentomatoes.com/api/public/v1.0/movies/771359313/similar.json"
}
}, {
"id": "771355766",
"title": "Big Hero 6",
"year": 2014,
"mpaa_rating": "PG",
"runtime": 93,
"critics_consensus": "",
"release_dates": {
"theater": "2014-11-07"
},
"ratings": {
"critics_rating": "Certified Fresh",
"critics_score": 89,
"audience_rating": "Upright",
"audience_score": 94
},
"synopsis": "With all the heart and humor audiences expect from Walt Disney Animation Studios, \"Big Hero 6\" is an action-packed comedy-adventure about robotics prodigy Hiro Hamada, who learns to harness his genius-thanks to his brilliant brother Tadashi and their like-minded friends: adrenaline junkie Go Go Tamago, neatnik Wasabi, chemistry whiz Honey Lemon and fanboy Fred. When a devastating turn of events catapults them into the midst of a dangerous plot unfolding in the streets of San Fransokyo, Hiro turns to his closest companion-a robot named Baymax-and transforms the group into a band of high-tech heroes determined to solve the mystery. (C) Disney",
"posters": {
"thumbnail": "http://content7.flixster.com/movie/11/17/85/11178581_tmb.jpg",
"profile": "http://content7.flixster.com/movie/11/17/85/11178581_tmb.jpg",
"detailed": "http://content7.flixster.com/movie/11/17/85/11178581_tmb.jpg",
"original": "http://content7.flixster.com/movie/11/17/85/11178581_tmb.jpg"
},
"abridged_cast": [{
"name": "Ryan Potter",
"id": "771360315",
"characters": ["Hiro Hamada"]
}, {
"name": "Scott Adsit",
"id": "406975480",
"characters": ["Baymax"]
}, {
"name": "T.J. Miller",
"id": "770690115",
"characters": ["Fred"]
}, {
"name": "Jamie Chung",
"id": "770694653",
"characters": ["Go Go Tomago"]
}, {
"name": "Damon Wayans Jr.",
"id": "770822247",
"characters": ["Wasabi"]
}],
"alternate_ids": {
"imdb": "2245084"
},
"links": {
"self": "http://api.rottentomatoes.com/api/public/v1.0/movies/771355766.json",
"alternate": "http://www.rottentomatoes.com/m/big_hero_6/",
"cast": "http://api.rottentomatoes.com/api/public/v1.0/movies/771355766/cast.json",
"reviews": "http://api.rottentomatoes.com/api/public/v1.0/movies/771355766/reviews.json",
"similar": "http://api.rottentomatoes.com/api/public/v1.0/movies/771355766/similar.json"
}
}],
"links": {
"self": "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?limit=2&country=us",
"alternate": "http://www.rottentomatoes.com/movie/box-office/"
},
"link_template": "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?limit={num-results}&country={country-code}"
}
Now, I managed to get name, id, but not the characters. Here are some parts of the code how I got it to work:
public class Movie {
String actor_name;
public Movie(String response, int index) {
Gson gson = new Gson();
MoviesContainer movie = gson.fromJson(response.trim(), MoviesContainer.class);
List < MovieData > movies = movie.movie
AbridgedCastData[] aCast = gson.fromJson(gson.toJson(movies.get(index).abridged_cast), AbridgedCastData[].class);
actor_name = aCast[0].name;
}
}
class MovieData {
Object abridged_cast;
}
class MoviesContainer {
public List < MovieData > movies;
}
class AbridgedCastData {
String name;
String id;
Object characters;
}
I'm using directly index for testing purposes, so actor_name works perfectly.
I tried like this :
CharactersData[] character = gson.fromJson(gson.toJson(aCast[0].characters), CharactersData[].class);
But I'm getting error:
Expected BEGIN_OBJECT but was STRING
I searched everywhere but I can't find how to access characters. How to get for example character Lloyd Christmas? Thanks in advance.
First of all your JSON file is not valid. It should begin with { and end with }. You can check with an online validator such as JSONLint. That's why you get this error.
Secondly if you look at the structure of the file, you see that there is an an array called abridged_cast which contains some objects (which you defined fine in your AbridgedCastData class).
So the final structure could be:
class A {
//contains a list of objects B or an array of objects B
}
class B {
//name
//id
//characters (list of Strings or String array)
}
We are almost done!
When you don't specify a SerializedName annotation, the parser requires that the field name of the attribute you want to serialize must be the same as in the JSON file (otherwise you will end up with a non-initialized value). Since that's not the case you need to add a #SerializedName("abridged_cast") annotation.
Finally you end up with:
public class Test {
public static void main(String[] args) throws FileNotFoundException {
BufferedReader br = new BufferedReader(new FileReader("myJson.json"));
Gson gson = new Gson();
MoviesContainer movie = gson.fromJson(br, MoviesContainer.class);
List<AbridgedCastData> movies = movie.movies;
System.out.println(movies);
}
}
class MoviesContainer {
#SerializedName("abridged_cast")
public List<AbridgedCastData> movies;
}
class AbridgedCastData {
String name;
String id;
List<String> characters;
#Override
public String toString() {
return "AbridgedCastData [name=" + name + ", id=" + id
+ ", characters=" + characters + "]";
}
}
Which outputs:
[AbridgedCastData [name=Jim Carrey, id=162659418, characters=[Lloyd Christmas]], AbridgedCastData [name=Jeff Daniels, id=162654392, characters=[Harry Dunne]], AbridgedCastData [name=Kathleen Turner, id=162658757, characters=[Fraida Felcher]], AbridgedCastData [name=Rob Riggle, id=770750133, characters=[Travis/Captain Lippincott]], AbridgedCastData [name=Jennifer Lawrence, id=770800260, characters=[Young Fraida Felcher]]]
you could change your response and then parse it.
response = "{" + response + "}" ;
// now parse json

Unable to get specific data from a JSON object

I am trying to extract specific data from a json response using org.json.JSONObject library
Heres is my json response :
{
"facets": {
"application": [
{
"name": "38",
"distribution": 1
}
],
"node": [
{
"name": "frstlwardu03_05",
"distribution": 1
}
],
"area": [
{
"name": "x",
"distribution": 1
}
],
"company": [
{
"name": "war001",
"distribution": 1
}
]
},
"duObjects": [
{
"id": "TASK|TSK(ZRM760J)(000)(ZRM760JU00)(000)|ZSRPSRM000",
"name": "TSK(ZRM760J)(000)(ZRM760JU00)(000)",
"mu": "ZSRPSRM000",
"label": "",
"session": "ZRM760J|000",
"sessionLabel": "SAP SRM Achats frais generaux execution",
"uprocHeader": "ZRM760JU00|000",
"uprocHeaderLabel": "Header for SRM760J",
"uprocHeaderType": "CL_INT",
"domain": "M",
"domainLabel": "",
"application": "38",
"applicationLabel": "magasin",
"highlightResult": {
"name": "name",
"word": "TSK"
}
}
],
"totalCount": 1,
"pageSize": 10,
"pageCurrent": 1,
"pageNb": 1
}
Here is the method I used to convert the URL call to a jsonobject :
public static JSONObject readJsonFromUrl(String url) throws IOException, JSONException
{
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-
8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
When I call this method I am able to get the data in teh Duobject :
public static void main(String[] args) throws IOException, JSONException {
JSONObject json = readJsonFromUrl("http://frstmwarwebsrv.orsyptst.com:9000/duobject?
searchString=TSK(ZRM760J)(000)(ZRM760JU00)
(000)&filterchecks=nameJob,nameWF,nameSWF,application,domain&p.index=0&p.size=10");
System.out.println(json.getJSONArray("duObjects"));
}
Is there anyway I can extract only the name field of the DuObjects?
You can use
System.out.println(json.getJSONArray("duObjects").getJSONObject(0).getString("name"));
to get the name.
1 : your complete response is a JSON OBJECT
2 : if any element is written like
"some key name " : { " some value " }
this is a JSON Object
3 : if any element is writen like
"some key name " : " some value "
this is value inside you json object which you can get by
jsonObject.getString("key name")
4 : if any element is writen like
"some key name " : [ " some value " ]
then this is a JSON Array and you have to take it in to a JSON ARRAY and then traverse its elements by
jsonObject.getJSONARRAY("key name for JSON ARRAY IN RESPONSE ")
and then you can traverse the elements of the JSON ARRAY by
`jsonArrayObj.get(0);`
You can use Jackson libraries to covert to java. Jackson api provides annotation level and it automatically converts json to pojo object and object to json vice versa . refer this link. you can get good idea about this
http://wiki.fasterxml.com/JacksonSampleSimplePojoMapper
http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/

JSON string is not being parsed

I want to parse a JSON string:
MyJsonString:
{
"status": "ok",
"count": 2,
"count_total": 9,
"pages": 5,
"posts": [
{
"id": 432,
"type": "post",
"title": "Title 1"
},
{
"id": 434,
"type": "post",
"title": "Title 2"
}
]
}
I have gone through:
http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/
http://p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-android-listview/
The examples work fine,but for that,i edited the JSON string to make it a Java String.
Ex:
JSON String:
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
I edited to:
String jsonStr = "{menu: {" +
"id: file," +
"value: File," +
"popup: {" +
"menuitem: [" +
"{value: New, onclick: CreateNewDoc()}," +
"{value: Open, onclick: OpenDoc()}," +
"{value: Close, onclick: CloseDoc()}" +
"]" +
"}" +
"}}";
But when i try to parse this myJsonString after accordingly editing it to be a valid Java String and run the project,it gives me warning and it does not display the Toast message which gives me titles.
Logcat:
10-19 18:36:45.972: WARN/System.err(1250): org.json.JSONException: Unterminated object at character 101 of { status : ok ,count : 2,count_total : 9,pages : 5,posts : [{id : 432,type : post ,title : Title 1 ,},{id : 434,type : post ,title : Title 2 ,},]}
I don't know where I am doing wrong? Even I have no idea,how to make Json String to a valid Java String programatically?
Any help appreciated.
Edit:
String jsonString="{\" status : ok \",\"count : 2\",\"count_total : 9\",\"pages : 5\",\"posts\" : [{\" id\" : \"432\",\"type\": \" post\", \"title\" : \" Title 1 \"},{ \"id \": \"434\",\type : post ,\"title\" : \" Title 2\"}]}";
JSONObject jsonObj = new JSONObject(jsonString);
String status_value = jsonObj.getString("status");
Toast.makeText(context,"Status_value= "+status_value, Toast.LENGTH_LONG).show();
I tried to toast status value this way.But I can't. Please help.
In your case the response of the JSON coming is not a valid one.
"count": 2, which is not the correct way it should be in double quotes like this
"count": "2", same way for the rest of the response String also.
UPDATED:
You exact JSONString that you have created is wrong, just replace my string and checkout.
First String
String jsonString = "{\"status\": \"ok\",\"count\": \"2\",\"count_total\": \"9\",\"pages\": \"5\",\"posts\":" +
"[{\"id\": \"432\",\"type\": \"post\",\"title\": \"Title 1\"}," +
"{\"id\": \"434\",\"type\": \"post\",\"title\": \"Title 2\"}]}";
Second String
String jsonStr = "{\"menu\": {\"id\": \"file\",\"value\": \"File\",\"popup\": {\"menuitem\": " +
"[{\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"},{\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}," +
"{\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";
The string in your java code is NOT a valid JSON string. you do not enclode the strings with quotes. try this one:
String example = "[\"a\", \"b\", \"c\"]";
This should give you a string array.

Categories

Resources