how to parse this in android with json - java

I want to parse this json in android. Can you help me how to parse, if i need to start from head to parse or from results for this I don't know. Can you help me
{
"head":
{
"link": [],
"vars": ["city", "country"]
},
"results":
{
"distinct": false,
"ordered": true,
"bindings":
[
{
"city":
{
"type": "uri",
"value": "http://dbpedia.org/resource/Ferizaj"
} ,
"country":
{
"type": "uri",
"value": "http://dbpedia.org/resource/Kosovo"
}
}
]
}
}

Okay, first of all the JSON string you've given is invalid. I've written my answer based on the correct version of the JSON string that you have provided
{
"head":
{
"link": [],
"vars": ["city", "country"]
},
"results":
{
"distinct": false,
"ordered": true,
"bindings":
[
{
"city":
{
"type": "uri",
"value": "http://dbpedia.org/resource/Ferizaj"
} ,
"country":
{
"type": "uri",
"value": "http://dbpedia.org/resource/Kosovo"
}
}
]
}
}
Now, to get the "values", you'll need to do this.
JSONObject jsonObject = new JSONObject(response);
JSONObject results = jsonObject.getJSONObject("results");
JSONArray bindings = results.getJSONArray("bindings");
for (int i = 0; i < bindings.length(); i++) {
JSONObject binding = bindings.getJSONObject(i);
JSONObject city = binding.getJSONObject("city");
// Get value in city
String cityValue = city.getString("value");
Log.d("CITY", cityValue);
JSONObject country = binding.getJSONObject("country");
// Get value in country
String countryValue = country.getString("value");
Log.d("COUNTRY", countryValue);
}

Related

Jolt returns null after transforming but same works at http://jolt-demo.appspot.com/#inception

I am trying to transform the below JSON:
From:
{
"id": 123,
"name": {
"firstName": "shiva",
"lastName": "kumar"
},
"dateOfBirth": "11/09/2012",
"emailId": "mymail#gmail.com",
"address": {
"addressLine1": "blr",
"addressLine2": "KA"
},
"salary": 12334
}
to:
{
"id": 123,
"email": "mymail#gmail.com",
"salary": 12334,
"fullname": {
"firstName": "shiva",
"lastName": "kumar"
},
"fullAdress": "blr KA"
}
Code: The below code just return null.
private JSONObject tranformRequest(String json, String specFile){
URI uri = Thread.currentThread().getContextClassLoader().getResource(specFile).toURI();
String jsonSpec = Files.readAllLines(Paths.get(uri)).stream().collect(Collectors.joining());
JSONArray jsonArray = new JSONArray(jsonSpec);
List<Map<String, Object>> list = new ArrayList<>();
for(int i = 0 ; i < jsonArray.length();i++){
list.add(jsonArray.getJSONObject(i).toMap());
}
Chainr chainr = Chainr.fromSpec(list);// JsonUtils.classpathToList( "/path/to/chainr/spec.json" );
Object output = chainr.transform( json );
return (JSONObject) output;
}
pom.xml
<dependency>
<groupId>com.bazaarvoice.jolt</groupId>
<artifactId>jolt-core</artifactId>
<version>0.1.7</version>
</dependency>
[
If jolt failed to convert your input JSON return null. So it can be for jolt specification.
Let's use the demo version of the site. Maybe the problem is solved.
Please update your package with version 0.1.1 like the jolt-demo website, and use the below code.
[
{
"operation": "shift",
"spec": {
"id": "&",
"name": "fullname",
"emailId": "email",
"salary": "salary",
"address": {
"*": "&1"
}
}
},
{
"operation": "modify-overwrite-beta",
"spec": {
"*": "=join(' ',#0)"
}
}
]
If you have any problem please say in the comment.

How to handle JsonObject to own Object

Now i take JsonObject from API like this:
Its XML object converted to JsonObject.
"Details": {
"row": [
{
"item": [
{
"name": "Account",
"value": 12521512
},
{
"name": "ACCNO",
"value": 4214
},
{
"name": "Number",
"value": 5436
}
]
},
"item": [
{
"name": "Account",
"value": 5789678
},
{
"name": "ACCNO",
"value": 6654
},
{
"name": "Number",
"value": 0675
}
]
},
But i need convert this object and send like this:
{
"Details": {
"row": [
{
"Account": 12521512,
"ACCNO": 4214,
"Number": 12412421
},
{
"Account": 5789678,
"ACCNO": 6654,
"Number": "0675"
}
]
}
}
I have rows more than 1000, i need faster way to handle.
How to handle, please help me
You could use the JSON-java library to parse your input and transform it to your desired format. Something like this works but you may need to adjust it to your needs:
JSONObject jsonObject = new JSONObject(json); // Load your json here
JSONObject result = new JSONObject("{\"Details\": {\"row\": []}}");
for (Object row : jsonObject.getJSONObject("Details").getJSONArray("row")) {
if (!(row instanceof JSONObject)) continue;
Map<Object, Object> values = new HashMap<>();
for (Object item : ((JSONObject) row).getJSONArray("item")) {
if (!(item instanceof JSONObject)) continue;
values.put(((JSONObject) item).get("name"), ((JSONObject) item).get("value"));
}
result.getJSONObject("Details").getJSONArray("row").put(values);
}
// Now result is in your format

Not able to Extract JSON response for Post call with Rest assured

Can someone help me in extracting the JSON response? I want to fetch the value for asset and ID and name under client and assert it in my code. Nothing is working for me to extract these values in my java code
[
{
"metadata": {
"asset": "ef59872625",
"customerInfo": {
"client": {
"id": "0CgIHVIA3",
"name": "JAssociates"
}
},
"adInfo": {
"title": "Te1",
"adId": "Te1",
"cartNumber": "98462",
"dueDate": "2021-06-23",
"dubber": {
"id": null,
"name": null,
"email": null
},
"archiveOn": "2021-06-29",
"eraseOn": "2021-09-24",
"length": {
"unit": "seconds",
"amount": 30
},
"creatID": 15813794
},
"targetInfo": [
{
"channelType": "AA",
"market": {
"id": 400,
"name": "Dallas, TX",
"Status": "Success",
"Status2": {
"state": "Submitted",
"message": null
}
}
}
]
},
"links": [
{
"href": "https://interntadata",
"type": "metadata"
},
{
"href": "https://interntent",
"type": "content"
}
]
}
]
Any pointers It would be a great help
1) First, get the response body by hitting the URL.
Response resp = RestAssured.given().headers("Content-Type", ContentType.JSON, "Accept", ContentType.JSON).
when().get("{{YOUR-URL}}").
then().contentType(ContentType.JSON).extract().response();
String responseBody = resp.getBody().asString();
2) Extract Value from JSON:
First Method: Using JsonPath
import io.restassured.path.json.JsonPath;
JsonPath js = new JsonPath(responseBody);
String asset = js.getString("metadata.asset");
System.out.println(asset);
String id = js.getString("metadata.customerInfo.client.id");
System.out.println(id);
String name = js.getString("metadata.customerInfo.client.name");
System.out.println(name);
Second Method:
import org.json.JSONArray;
import org.json.JSONObject;
JSONArray object = new JSONArray(responseBody);
JSONObject metadataObj = ((JSONObject)object.get(0)).getJSONObject("metadata");
String asset = metadataObj.getString("asset");
System.out.println(asset);
JSONObject customerInfoObject = metadataObj.getJSONObject("customerInfo");
JSONObject clientObject = customerInfoObject.getJSONObject("client");
String id = clientObject.getString("id");
System.out.println(id);
String name = clientObject.getString("name");
System.out.println(name);
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>LATEST</version>
</dependency>

Add hashmap having possible serialized JSON values to a JSON string as a node

What is the cheapest way to take the jsonstring and hashmap below and produce the result in JAVA?
pseudocode data example:
String jsonstring = {
"people": {
"name": "name1",
},
"addresses": {
"address1": {
"number": "1234",
"city": "europa"
}
}
}
HashMap hashmap = {
["string.a.1"] = "stringa1",
["string.a.2"] = "stringa2",
["object.a.1"] = "{/"item1/":/"value1/"}" // serialized JSON object
}
String result = {
"people": {
"name": "name1",
},
"addresses": {
"address1": {
"number": "1234",
"city": "europa"
}
},
"buffer": {
"string.a.1": "stringa1",
"string.a.2": "stringa2",
"object.a.1": {
"item1": "value1"
}
}
}
Thanks in advance for any help.

Parse Json String (Feed RSS file) in Android

How can I parse this piece of JSON code?
{
"direction": "ltr",
"id": "feed/http => //www.theverge.com/rss/full.xml",
"title": "The Verge - All Posts",
"continuation": "CLKM0OyU0rYC",
"self": [
{
" href": "https => //cloud.feedly.com/reader/3/stream/contents/feed%2Fhttp%3A%2F%2Fwww.theverge.com%2Frss%2Ffull.xml?n=20&unreadOnly=true"
}
],
"alternate": [
{
"href": "http://www.theverge.com/",
"type": "text/html"
}
],
"updated": 1367539068016,
"items": [
{
"id": "entryId",
"unread": true,
"categories": [
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/tech",
"label": "tech"
}
],
"tags": [
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/tag/inspiration",
"label": "inspiration"
}
],
"title": "NBC's reviled sci-fi drama 'Heroes' may get a second lease on life as Xbox Live exclusive",
"published": 1367539068016,
"updated": 1367539068016,
"crawled": 1367539068016,
"alternate": [
{
"href": "http://www.theverge.com/2013/4/17/4236096/nbc-heroes-may-get-a-second-lease-on-life-on-xbox-live",
"type": "text/html"
}
],
"content": {
"direction": "ltr",
"content": "..."
},
"author": "Nathan Ingraham",
"origin": {
"streamId": "feed/http://www.theverge.com/rss/full.xml",
"title": "The Verge - All Posts",
"htmlUrl": "http://www.theverge.com/"
},
"engagement": 15
},
{
"id": "entryId2",
"unread": true,
"categories": [
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/category/tech",
"label": "tech"
}
],
"tags": [
{
"id": "user/c805fcbf-3acf-4302-a97e-d82f9d7c897f/tag/inspiration",
"label": "inspiration"
}
],
"title": "Senate rejects bipartisan gun control measure for background checks despite broad public support",
"published": 1367539068016,
"updated": 1367539068016,
"crawled": 1367539068016,
"alternate": [
{
"href": "http://www.theverge.com/2013/4/17/4236136/senate-rejects-gun-control-amendment",
"type": "text/html"
}
],
"content": {
"direction": "ltr",
"content": "...html content..."
},
"author": "T.C. Sottek",
"origin": {
"streamId": "feed/http://www.theverge.com/rss/full.xml",
"title": "The Verge - All Posts",
"htmlUrl": "http://www.theverge.com/"
},
"engagement": 39
}
]
}
That is my solution but it doesn't work... what is my error? thanks
try{
//JSONArray elements = new JSONArray (response);
JSONObject json=new JSONObject(response);
JSONArray elements = json.getJSONArray("items");
Log.d(TAG, "Elemenenti numero" +elements.length());
// Getting Array of Contacts
// looping through All Contacts
for(int i = 0; i < elements.length(); i++){
JSONObject c = elements.getJSONObject(i);
// Storing each json item in variable
String identifier = c.getString("id");
String title = c.getString("title");
String link = c.getString("originId");
String data = c.getString("published");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date date=new Date();
try {
date = format.parse(data);
System.out.println(date);
} catch (Exception e) {
e.printStackTrace();
}
JSONObject summaryObj= c.getJSONObject("summary");
String summary = summaryObj.getString("content");
JSONObject contentObj= c.getJSONObject("content");
String content = contentObj.getString("content");
JSONObject sourceObj= c.getJSONObject("origin");
String source = contentObj.getString("title");
if (summary.length()==0 && content.length()!=0) summary=content;
if (content.length()==0 && summary.length()!=0) content=summary;
String image=this.getFirstImage(content);
FeedItem toAdd=new FeedItem(identifier, title, link, date, null, summary, content, image, source);
toAdd.toString();
}
}catch (JSONException e) {
e.printStackTrace();
}
JSONObject summaryObj= c.getJSONObject("summary");
There is no element called summary, you may try
if(c.has("summary")) {
JSONObject summaryObj= c.getJSONObject("summary");
}
if that doesn't work, please post your stacktrace, (logcat)
You don't have any tag named "originID". but you are trying to get String from it.
Similarly,you don't have tag "summary" also but you are trying to get JSONObject from it.

Categories