parse json news feed array android - java

I have an json feed from bbc in this format
{
"name": "ticker",
"entries": [
{
"headline": "text",
"prompt": "LATEST",
"isBreaking": "false",
"mediaType": "Standard",
"url": ""
},
{
"headline": "text",
"prompt": "LATEST",
"isBreaking": "false",
"mediaType": "Standard",
"url": ""
},
etc...........
My code is as follows:
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions.getJSONfromURL("http:/......");
try{
JSONArray item = json.getJSONArray("entries");
for (int i = 0; i<item.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = item.getJSONObject(i);
JSONObject title = e.JSONObject("headline");
map.put("title", "Title:" + e.getString("headline");
}
}
It gives me the error "java.lang.String cannot be converted to JSONObject"
I also tried leaving out JSONObject title = e.JSONObject("headline"); and it gives me a path error (note

You want e.getString("headline"), not e.JSONObject

use
JSONObject e = item.getJSONObject(i);
map.put("title", "Title:" + e.getString("headline");
instead of
JSONObject e = item.getJSONObject(i);
JSONObject title = e.JSONObject("headline");
map.put("title", "Title:" + e.getString("headline");
becuase e json object not contain any other json object it only contains keys and corresponding values

Related

how to covert JSONObject to another Required JSONObect by mapping AccountId using java

**My result of JSONObject to convert as follows bellow code and have searched for many this how to convert using java but I converted that **
{
"result": {
"accountnames": [{
"accountName": "Hari",
"accountId": 878488
}, {
"accountName": "ravi",
"accountId": 878487
}],
"sales": [{
"accountSales": "89",
"accountId": 878488
}, {
"accountName": "98",
"accountId": 878487
}],
"countResult": [{
"accountResult": "945",
"accountId": 878488
}, {
"accountResult": "9452",
"accountId": 878489
}]
}
}
*and this is where the sample code to be converted *
{
"result": [{
"accountName": "Hari",
"accountSales": "89",
"accountResult": "945",
"accountId": 878488
},
{
"accountName": "ravi",
"accountSales": "98",
"accountId": 878487
},
{
"accountResult": "9452",
"accountId": 878489
}
]
}
My required JSON data has to be formatted as below
You need to group all the elements by accountId. You can use something like this depending on the json library that you are using.
Initialize the json object:
JSONObject rootJson = new JSONObject(json);
JSONObject resultJson = rootJson.getJSONObject("result");
Create a map to hold the objects by accountId:
Map<String, JSONObject> accountIds = new HashMap<>();
Then iterate for each key in the json, then for each element in the arrays and then for each property of the object inside the json:
Iterator mainKeys = resultJson.keys();
while (mainKeys.hasNext()) {
String key = (String) mainKeys.next();
JSONArray array = resultJson.getJSONArray(key);
for (int index = 0; index < array.length(); index++) {
JSONObject object = array.getJSONObject(index);
if (object.has("accountId")) {
String accountId = object.get("accountId").toString();
JSONObject accum = accountIds
.computeIfAbsent(accountId, (k) -> new JSONObject());
// depending on the json impl you can use putAll or similar
Iterator objKeys = object.keys();
while (objKeys.hasNext()) {
String property = (String) objKeys.next();
accum.put(property, object.get(property));
}
} else {
// does not have account id, ignore or throw
}
}
}
Finally create the json file and add the elements to the JSONArray:
JSONObject finalJson = new JSONObject();
finalJson.put("result", new JSONArray(accountIds.values()));
System.out.println(finalJson.toString());
(note: the json has an error in sales array accountName instead of accountSales)

org.json.JSONException: No value for Name JSON extraction error

I am getting this error when I try to get the value for "Name" out of the following JSON:
{
"edges": [
{
"node": {
"Name": "Sunday River",
"Latitude": 44.4672,
"Longitude": 70.8472
}
},
{
"node": {
"Name": "Sugarloaf Mountain",
"Latitude": 45.0314,
"Longitude": 70.3131
}
}
]
}
This is the snippet of code I am using to try and access these values, but I am just testing getting "Name" for now:
String[] nodes = stringBuilder.toString().split("edges");
nodes[1] = "{" + "\"" + "edges" + nodes[1];
String s = nodes[1].substring(0,nodes[1].length()-3);
Log.d(TAG, s);
JSONObject json = new JSONObject(s);
JSONArray jsonArray = json.getJSONArray("edges");
ArrayList<String> allNames = new ArrayList<String>();
ArrayList<String> allLats = new ArrayList<String>();
ArrayList<String> allLongs = new ArrayList<String>();
for (int i=0; i<jsonArray.length(); i++) {
JSONObject node = jsonArray.getJSONObject(i);
Log.d(TAG, node.toString(1));
String name = node.getString("Name");
Log.d(TAG, name);
}
My output looks like this:
{"edges":[{"node":{"Name":"Sunday River","Latitude":44.4672,"Longitude":70.8472}},{"node":{"Name":"Sugarloaf Mountain","Latitude":45.0314,"Longitude":70.3131}}]}}
{
"node": {
"Name": "Sunday River",
"Latitude": 44.4672,
"Longitude": 70.8472
}
}
org.json.JSONException: No value for Name
I understand that I could use optString and not get the error, but that will not give me the data stored in each node.
Here is a version that works with your unaltered JSON:
public static void main(String... args)
{
String json = "{\"data\":{\"viewer\":{\"allMountains\":{\"edges\":[{\"node\":{\"Name\":\"Sunday River\",\"Latitude\":44.4672,\"Longitude\":70.8472}},{\"node\":{\"Name\":\"Sugarloaf Mountain\",\"Latitude\":45.0314,\"Longitude\":70.3131}}]}}}}";
JSONObject obj = new JSONObject(json);
JSONObject data = obj.getJSONObject("data");
JSONObject viewer = data.getJSONObject("viewer");
JSONObject allMountains = viewer.getJSONObject("allMountains");
// 'edges' is an array
JSONArray edges = allMountains.getJSONArray("edges");
for (Object edge : edges) {
// each of the elements of the 'edge' array are objects
// with one property named 'node', so we need to extract that
JSONObject node = ((JSONObject) edge).getJSONObject("node");
// then we can access the 'node' object's 'Name' property
System.out.println(node.getString("Name"));
}
}

How do i refactor one JSON array into other format in JAVA?

I have a JSON array like this,
JSONArray content=
"[
{"+"\"pageid\":\"19\","+"\"company\":"+"\"C1\","+"\"pageview\":"+"\"10\","+"\"visitfreq\":"+"\"2\"},{"+"\"pageid\":\"19\","+"\"company\":"+"\"C2\","+"\"pageview\":"+"\"20\","+"\"visitfreq\":"+"\"4\"},{"+"\"pageid\":\"200\","+"\"company\":"+"\"C3\","+"\"pageview\":"+"\"30\","+"\"visitfreq\":"+"\"3\"}
]";
Code for JSONArray:
JSONObject jObj1 = new JSONObject();
jObj1.put("pageid", "19");
jObj1.put("company", "C1");
jObj1.put("pageview", "10");
jObj1.put("visitfreq", "2");
JSONObject jObj2 = new JSONObject();
jObj2.put("pageid", "19");
jObj2.put("company", "C2");
jObj2.put("pageview", "20");
jObj2.put("visitfreq", "4");
JSONObject jObj3 = new JSONObject();
jObj3.put("pageid", "200");
jObj3.put("company", "C3");
jObj3.put("pageview", "30");
jObj3.put("visitfreq", "3");
JSONArray jArr = new JSONArray();
jArr.put(jObj1);
jArr.put(jObj2);
jArr.put(jObj3);
Visual representation:
[
{
"company": "C1",
"visitfreq": "2",
"pageview": "10",
"pageid": "19"
},
{
"company": "C2",
"visitfreq": "4",
"pageview": "20",
"pageid": "19"
},
{
"company": "C3",
"visitfreq": "3",
"pageview": "30",
"pageid": "200"
}
]
I have worked on it to get an out put like below
the out put like this
[{pageid},[{rest of details}] ,{pageid},[{rest of details}] ]
if same pageid occur more than once
it should be like this
[{pageid},[{rest of details1},{rest of details2},.. ],{pageid},[{rest of details}] ]
Looks like you need to create a Map that maps pageid : [{rest of details1},{rest of details2},.. ].
Once you have that Map, you can transform it into your desired output.
Here is the code that will take your JSONArray (the one in the code above) and turn it into Map<String, JSONArray>.
public Map<String, JSONArray> getJsonArrayAsMapOnPageId(JSONArray inputArr) throws JSONException {
//Map holding pageid : [{company:"",pageview:"",visitfreq:""}, ... , ...] mappings
Map<String, JSONArray> idMap = new HashMap<String, JSONArray>();
for (int i=0; i < inputArr.length(); i++) {
JSONObject inputObj = inputArr.getJSONObject(i);
String id = inputObj.getString("pageid");
JSONArray jObjList;
if (idMap.containsKey(id)) {
//append to existing list in the Map
jObjList = idMap.get(id);
} else {
//create new list
jObjList = new JSONArray();
}
JSONObject newJsonObj = new JSONObject();
newJsonObj.put("company", inputObj.get("company"));
newJsonObj.put("pageview", inputObj.get("pageview"));
newJsonObj.put("visitfreq", inputObj.get("visitfreq"));
jObjList.put(newJsonObj);
idMap.put(id, jObjList);
}
return idMap;
}
Here is what it'll look like:
System.out.println("Map looks like:\n" + pageidMap);
Here is what I got:
{
200=[
{
"company": "C3",
"visitfreq": "3",
"pageview": "30"
}
],
19=[
{
"company": "C1",
"visitfreq": "2",
"pageview": "10"
},
{
"company": "C2",
"visitfreq": "4",
"pageview": "20"
}
]
}
I'm not sure exactly in what form (Object, print to output, etc) you want this output to be in, so you can do the final bit of transforming this Map<String, JSONArray> into [{pageid},[{rest of details1},{rest of details2},.. ],{pageid},[{rest of details}] ] without problems.

Parsing Json in Android with out using any external libraries

I converted a map to a Json String using the code below
String msg = new JSONObject(map).toString();
How do I parse the above Json String to get the map back in Android with out using any external libraries?
If you have pairs of String/String you can easily restore it this way:
JSONObject obj = new JSONObject(msg);
Iterator<String> keys = obj.keys();
HashMap<String, String> map = new HashMap<String, String>();
while(keys.hasNext()) {
String key = keys.next();
map.put(key, obj.optString(key));
}
You are asking how to parse but I don't see any JSON to parse in your question.
An example parsing method without any library looks like that:
JSONObject jo = new JSONObject(response);
JSONArray rootArray= jo.getJSONArray("jArray");
int rootArrayLength=rootArray.length();
for(int i=0;i<rootArrayLength;i++){
int id= rootArray.getJSONObject(i).getInt("value");
// do same for others too and create an object
}
// create object and make a list
You can also check from my other answer to compare:
Convert String to JsonArray
You can check my answer here for JSON Parsing:
https://stackoverflow.com/questions/21872643/about-json-parsing-exchange-data-with-rest-services/21872688#21872688
For completeness, please find the details below:
JSONObject is the key class for JSON Parsing. This class represent JSON data in key/value pair where values can be of any type: JSONObjects, JSONArrays, Strings, Booleans, Integers, Longs, Doubles
You create JSONObject as:
JSONObject jObject = new JSONObject(result);
where result is the response you obtain from your HTTPRequest.
Use this jObject to get different types using the specific names:
String:
String jsonString = jObject.getString("NAME");
Array:
JSONArray jsonArray = jObject.getJSONArray("NAME");
Eg. For parsing the places results I used following function, where JSON is something like:
"results" : [
{
"geometry" : {
"location" : {
"lat" : 36.817729,
"lng" : 10.18206
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "35a4f720fff88e2cfb94d64bfd7dbe95a8b4a632",
"name" : "Banque Al-Baraka",
"reference" : "CoQBcwAAAJbocdTKVg8I8CzgDdNtBQQaMsaghRlks-IWYl9eDNmFtftPHMgEfVeek_NHJZ2AN9JbiMda1WvREmoeIHBHsNdz9i7gtBaLM1xB93uhema_oswpqD-eRQ9b3fvTo4MhTOeIa7cRJ70BSEtDMONZqFyjqlGvL-5WsiwmqI1F3Vp_EhArWzyFuNrJdly2cHRBNxUJGhQjlcyHs-U2F0ILpN-ce-PHEesdqA",
"types" : [ "bank", "finance", "establishment" ],
"vicinity" : "88 P9, Tunis"
},
{
"geometry" : {
"location" : {
"lat" : 36.861635,
"lng" : 10.164628
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "da42093835270f902f64bc870154e6787fffbc7b",
"name" : "Agence Ennasr",
"reference" : "CnRwAAAAoh-XuMXghUKtv2UtHQJiRXB0ZugUnAkJIyP-vBd2YzTj5GdwIb5XhUS9x5-uY9_OwyQUdMmUeDHYm4KXHFNvOoj7diOOHAGBu-xCI4svIxcCwQ2w063mc2G3lohiScYMNpbKhwnCaggt0H1iknZY6xIQxDvNwVN0wWkVwO8zf_El5hoUwHgmgFflE31LDLj2_rr0uc1zvZM",
"types" : [ "bank", "finance", "establishment" ],
"vicinity" : "Avenue de Hédi Nouira, Ariana"
},
]
Parsing JSON Array
public ArrayList<HashMap<String,String>> parseResult(JSONObject jsonObject) throws JSONException {
JSONArray jsonArray = jsonObject.getJSONArray(Constants.RESULTS);
ArrayList<HashMap<String, String>> placesList = new ArrayList<HashMap<String,String>>();
for (int i = 0; i < jsonArray.length(); i++) {
Object object = jsonArray.get(i);
if (object instanceof JSONObject) {
placesList.add(parsePlaceInfo((JSONObject) object));
}
}
return placesList;
}
Parsing simple JSON Object
private HashMap<String, String> parsePlaceInfo(JSONObject place) throws JSONException {
String name = place.getString(Constants.NAME);
String icon = place.getString(Constants.ICON);
String vicinity = place.getString(Constants.VICINITY);
JSONObject locationObject = place.getJSONObject(Constants.GEOMETRY).getJSONObject(Constants.LOCATION);
String lat = locationObject.getString(Constants.LAT);
String lng = locationObject.getString(Constants.LNG);
HashMap<String, String> placeDetails = new HashMap<String, String>();
placeDetails.put(Constants.NAME, name);
placeDetails.put(Constants.ICON, icon);
placeDetails.put(Constants.VICINITY, vicinity);
placeDetails.put(Constants.LAT, lat);
placeDetails.put(Constants.LNG, lng);
return placeDetails;
}
Please note that this is not a complete code. I am providing you main details. Please let me know if you need any specific details regarding the code. Thanks!

Parsing a JSON object within a JSON object

I have a JSON file which contains an array of item objects:
{
"item": [
{
"title": "TitleA",
"link": "http://www.abc.html?partner=rss&emc=rss",
"guid": {
"-isPermaLink": "true",
"#text": "www.abc.html"
},
"atom:link": {
"-rel": "standout",
"-href": "http://www.abc.html?partner=rss&emc=rss"
},
"media:content": {
"-url": "standard.jpg",
"-medium": "image",
"-height": "75",
"-width": "75"
},
"media:description": "This is the description.",
"media:credit": "Reuters",
"description": "In depth description",
"dc:creator": "By test creator",
"pubDate": "Sun, 21 Oct 2012 11:29:12 GMT",
"category": "World"
},
{
"title": "TitleB",
"link": "http://www.abc.html?partner=rss&emc=rss",
"guid": {
"-isPermaLink": "true",
"#text": "www.abc.html"
},
"atom:link": {
"-rel": "standout",
"-href": "http://www.abc.html?partner=rss&emc=rss"
},
"media:content": {
"-url": "standard.jpg",
"-medium": "image",
"-height": "75",
"-width": "75"
},
"media:description": "This is the description.",
"media:credit": "Reuters",
"description": "In depth description",
"dc:creator": "By test creator",
"pubDate": "Sun, 21 Oct 2012 11:29:12 GMT",
"category": "World"
}
]
}
Now I know how to get the "title", but I don't know how I would access the "-url" within "media:content" for example, since it seems to be a JSON object within the Item object. How would I get this value and assign it to a value in my Item class?
try as to get "-url" within "media:content" from current json string :
JSONObject jsonObject = new JSONObject("Your JSON STRING HERE");
JSONArray jsonArray =jsonObject.getJSONArray("item");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObjectitem=
jsonArray.getJSONObject(i);
// get title or link here
String strtitle=jsonObjectitem.getString("title");
//....get other values in same way
// get media:content json object
JSONObject jsonObjectmediacontent =
jsonObjectitem.getJSONObject("media:content");
// get url,medium,...
String strurl=jsonObjectmediacontent.getString("-url");
//....get other values in same way
}
Write below code to parse -url string, it will solve your problem.
JSONObject mMainJsonObj = new JSONObject("Pass Json Response String Here");
JSONArray mItemJsonArray = mMainJsonObj.getJSONArray("item");
for (int i = 0; i < mItemJsonArray.length(); i++) {
JSONObject mJsonObj1 = mItemJsonArray.getJSONObject(i);
String mTitle = mJsonObj1.getString("title");
String mLink = mJsonObj1.getString("link");
JSONObject mJsonObjGuid = mJsonObj1.getJSONObject("guid");
String mIsPermLink = mJsonObjGuid.getString("-isPermaLink");
String mText = mJsonObjGuid.getString("#text");
JSONObject mJsonObjAtomLink = mJsonObj1.getJSONObject("atom:link");
String mRel = mJsonObjAtomLink.getString("-rel");
String mHref = mJsonObjAtomLink.getString("-href");
JSONObject mJsonObjMediaContent = mJsonObj1.getJSONObject("media:content");
String mUrl = mJsonObjMediaContent.getString("-url");
String mMedium = mJsonObjMediaContent.getString("-medium");
String mHeight = mJsonObjMediaContent.getString("-height");
String mWidth = mJsonObjMediaContent.getString("-width");
}
And see below link for more information.
Json Parsing Example
Solution with Jackson: read your JSON into a JsonNode using an ObjectMapper and retrieve your values like this:
// Since JsonNode implements Iterable of itself and cycles through array elements,
// this works
for (final JsonNode element: node)
doSomethingWith(element.get("media:content").get("-url"));

Categories