I have a response received from sharepoint.
{
"d": {
"query": {
"SecondaryQueryResults": {
"__metadata": {
"type": "Collection(Microsoft.Office.Server.Search.REST.QueryResult)"
},
"results": []
},
"SpellingSuggestion": "",
"TriggeredRules": {
"__metadata": {
"type": "Collection(Edm.Guid)"
},
"results": ["e0205660-4971-4574-aa40-af6b4383cadd"]
},
"ElapsedTime": 224,
"__metadata": {
"type": "Microsoft.Office.Server.Search.REST.SearchResult"
},
"Properties": {
"__metadata": {
"type": "Collection(SP.KeyValue)"
},
"results": [{
"ValueType": "Edm.Int32",
"Value": "10",
"Key": "RowLimit"
}, {
"ValueType": "Edm.Guid",
"Value": "8413cd39-2156-4e00-b54d-11efd9abdb49",
"Key": "SourceId"
}, {
"ValueType": "Edm.Guid",
"Value": "7bc4ba9e-80ff-7000-58cf-f7ac556d1e34",
"Key": "CorrelationId"
}, {
"ValueType": "Edm.Boolean",
"Value": "false",
"Key": "WasGroupRestricted"
}, {
"ValueType": "Edm.Boolean",
"Value": "false",
"Key": "IsPartial"
}, {
"ValueType": "Edm.Boolean",
"Value": "false",
"Key": "HasParseException"
}, {
"ValueType": "Edm.String",
"Value": "en",
"Key": "WordBreakerLanguage"
}, {
"ValueType": "Edm.Boolean",
"Value": "false",
"Key": "IsPartialUpnDocIdMapping"
}, {
"ValueType": "Edm.Boolean",
"Value": "true",
"Key": "EnableInterleaving"
}, {
"ValueType": "Edm.Boolean",
"Value": "false",
"Key": "IsMissingUnifiedGroups"
}, {
"ValueType": "Edm.String",
"Value": "i62456",
"Key": "Constellation"
}, {
"ValueType": "Edm.String",
"Value": "<Query Culture=\"en-US\" EnableStemming=\"True\" EnablePhonetic=\"False\" EnableNicknames=\"False\" IgnoreAllNoiseQuery=\"True\" SummaryLength=\"180\" MaxSnippetLength=\"180\" DesiredSnippetLength=\"90\" KeywordInclusion=\"0\" QueryText=\"59055305\" QueryTemplate=\"\" TrimDuplicates=\"True\" Site=\"e297bd2b-597a-4f54-8509-e2febb91b869\" Web=\"d42ff0d1-883b-4545-ab6a-97b0401025d4\" KeywordType=\"True\" HiddenConstraints=\"\" \/>",
"Key": "SerializedQuery"
}]
},
"PrimaryQueryResult": {
"RefinementResults": null,
"SpecialTermResults": null,
"QueryId": "0585a5f1-89bc-43c1-b736-e163b4d7c1dd",
"QueryRuleId": "00000000-0000-0000-0000-000000000000",
"CustomResults": {
"__metadata": {
"type": "Collection(Microsoft.Office.Server.Search.REST.CustomResult)"
},
"results": []
},
"__metadata": {
"type": "Microsoft.Office.Server.Search.REST.QueryResult"
},
"RelevantResults": {
"Table": {
"__metadata": {
"type": "SP.SimpleDataTable"
},
"Rows": {
"results": [{
"__metadata": {
"type": "SP.SimpleDataRow"
},
"Cells": {
"results": [{
"ValueType": "Edm.Double",
"Value": "26.8860855102549",
"__metadata": {
"type": "SP.KeyValue"
},
"Key": "Rank"
}, {
"ValueType": "Edm.Int64",
"Value": "17594532057853",
"__metadata": {
"type": "SP.KeyValue"
},
"Key": "DocId"
}, {
"ValueType": "Edm.Int64",
"Value": "17594531057253",
"__metadata": {
"type": "SP.KeyValue"
},
"Key": "WorkId"
}, {
"ValueType": "Edm.String",
"Value": "Customer Request Filling",
"__metadata": {
"type": "SP.KeyValue"
},
"Key": "Title"
}, {
"ValueType": "Edm.String",
"Value": "Technology Services;svc ECMWise",
"__metadata": {
"type": "SP.KeyValue"
},
"Key": "Author"
}, {
"ValueType": "Edm.Int64",
"Value": "97182",
"__metadata": {
"type": "SP.KeyValue"
},
"Key": "Size"
}, {
"ValueType": "Edm.String",
"Value": "https:\/\/xxxxxx.sharepoint.com\/sites\/news\/CUST\/Forms\/Appeals\/Customer Reader.pdf",
"__metadata": {
"type": "SP.KeyValue"
},
"Key": "Path"
}, {
"ValueType": "Null",
"Value": null,
"__metadata": {
"type": "SP.KeyValue"
},
....
What I am trying to get is the "Path" of "Value" string of that pdf as a snapshot from below (part of section from what was above)
{
"ValueType": "Edm.String",
"Value": "https:\/\/xxxxxx.sharepoint.com\/sites\/news\/CUST\/Forms\/Appeals\/Customer Reader.pdf",
"__metadata": {
"type": "SP.KeyValue"
},
"Key": "Path"
}
I have tried to use JSONObject to parse it like this.
JSONObject jsonObject = (JSONObject) parser.parse(new InputStreamReader((httpConn.getInputStream())));
JSONObject folder = (JSONObject)jsonObject.get("d");
JSONObject query = (JSONObject) folder.get("query");
JSONObject properties = (JSONObject) query.get("PrimaryQueryResult");
JSONObject result = (JSONObject) properties.get("RelevantResults");
JSONObject table = (JSONObject) result.get("Table");
JSONObject rows = (JSONObject) table.get("Rows");
....
I was wondering if there is a easier way to do this or what if one of the key is not populated. It would throw null pointer exception so is there a way just to find a key directly inside of this long nested json and how do I get the field "Key" from the json array of the "Cells"
You should consider using a JSON serializer such as Jackson or GSON.
If the underlying JSON response structure will be the same for each call, even if it has missing keys, you can create your own POJO using something like JSONSchema2POJO. This will generate a POJO with Jackson or GSON annotations using a JSON string that you provide. Here's an example using a snippet of your JSON string:
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("ValueType")
#Expose
private String valueType;
#SerializedName("Value")
#Expose
private String value;
#SerializedName("__metadata")
#Expose
private Metadata metadata;
#SerializedName("Key")
#Expose
private String key;
public String getValueType() {
return valueType;
}
public void setValueType(String valueType) {
this.valueType = valueType;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public Metadata getMetadata() {
return metadata;
}
public void setMetadata(Metadata metadata) {
this.metadata = metadata;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
}
-----------------------------------com.example.Metadata.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Metadata {
#SerializedName("type")
#Expose
private String type;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
This is standard practice when consuming JSON in Java and it allows keys/values to be null when the object is serialized without breaking your code.
If the JSON structure is completely unpredictable, GSON allows you to create Generic types or you can take it a step further and write custom serializers. Jackson likely has similar functionality but I'm only versed in GSON.
You could use quick-json (enter link description here) and have something like this (rapid version not optimized) :
public class Go {
public static void main(String[] args) {
try {
List<String> pdf_list = new ArrayList<>();
JsonParserFactory factory= JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson("/54424034/sharepoint.json", "UTF-8");
//jsonMap.get("d/query/PrimaryQueryResult/RelevantResults/Table/Rows/results");
Map d = (Map) jsonMap.get("d");
Map query = (Map) d.get("query");
Map primaryQueryResult = (Map) query.get("PrimaryQueryResult");
Map relevantResults = (Map) primaryQueryResult.get("RelevantResults");
Map table = (Map) relevantResults.get("Table");
Map rows = (Map) table.get("Rows");
List<Map> results_rows = (ArrayList) rows.get("results");
for (Map result_row : results_rows) {
Map cells = (Map) result_row.get("Cells");
List<Map> results_cells = (ArrayList) cells.get("results");
for (Map result_cell : results_cells) {
String key = (String) result_cell.get("Key");
if ("Path".equalsIgnoreCase(key)) {
pdf_list.add((String) result_cell.get("Value"));
}
}
}
System.out.println(pdf_list);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
It just parses your Json and add all pdf path into a List
Related
I have a response which contains values which I need.
private void getDataFromDistanceMatrixToSaveAndAddToList(
GRATestDataImport place, String response) {
JSONObject responseAsJson = new JSONObject(response).getJSONArray("rows")
.getJSONObject(0)
.getJSONArray("elements")
.getJSONObject(0);
}
'response' in params includes:
{
"destination": [
"54.375,18.59"
],
"origin": [
"54.001,21.721"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "304.4 km",
"value": 304403
},
"duration": {
"text": "3 h 53 min",
"value": 14003
},
"status": "OK"
}
]
}
],
"status": "OK"
}
value: 'responseAsJson' in my method is:
{
"duration": {
"text": "3 h 53 min",
"value": 14003
},
"distance": {
"text": "304.4 km",
"value": 304403
},
"status": "OK"
}
How can I get value from the duration and the distance ?
you'll just have to navigate along
int duration = responseAsJson.getJSONObject("duration").getInt("value");
int distance = responseAsJson.getJSONObject("distance").getInt("value");
public class YourResponse
{
public string duration { get; set; }
public string distance { get; set; }
}
YourResponse response = JsonSerializer.Deserialize<YourResponse>(result);
I have a JSON array below, I want to be able to set label names that make sense instead of the entity names. Am generating tables dynamically using this data, I want the rows to have names that make more sense to the end user by assigning custom Label names. the recordtype generates new tab names
This is my JSON
[
{
"country": "USA",
"projectId": "USAID2020,
"case": "2014",
"recordType": "Identification",
"itemDetails": [
{
"ItemValue": "023",
"Label": "hA",
"ItemValueLabel": "023",
"Name": "hA"
},
{
"ItemValue": "0005",
"Label": "hUM",
"ItemValueLabel": "0005",
"Name": "hUM"
},
{
"ItemValue": "5",
"Label": "hCounty",
"ItemValueLabel": "5",
"Name": "hCounty"
}
]
},
{
"country": "USA",
"projectId": "USAID2020",
"case": "2014",
"recordType": "Eligibility",
"itemDetails": [
{
"ItemValue": "023",
"Label": "hA",
"ItemValueLabel": "023",
"Name": "hA"
},
{
"ItemValue": "0005",
"Label": "hUM",
"ItemValueLabel": "0005",
"Name": "hUM"
},
{
"ItemValue": "0005",
"Label": "hPUM",
"ItemValueLabel": "0005",
"Name": "hPUM"
}
]
}
]
This is how I want the labels to appear
[
{
"country": "USA",
"projectId": "USAID2020,
"case": "2014",
"recordType": "Identification",
"itemDetails": [
{
"ItemValue": "023",
"Label": "Area Code",
"ItemValueLabel": "023",
"Name": "hA"
},
{
"ItemValue": "0005",
"Label": "Manager Identification",
"ItemValueLabel": "0005",
"Name": "hUM"
},
{
"ItemValue": "5",
"Label": "County Name",
"ItemValueLabel": "5",
"Name": "hCounty"
}
]
},
{
"country": "USA",
"projectId": "USAID2020",
"case": "2014",
"recordType": "Eligibility",
"itemDetails": [
{
"ItemValue": "023",
"Label": "Area Code",
"ItemValueLabel": "023",
"Name": "hA"
},
{
"ItemValue": "0005",
"Label": "Manager Identification",
"ItemValueLabel": "0005",
"Name": "hUM"
},
{
"ItemValue": "0005",
"Label": "House Code",
"ItemValueLabel": "0005",
"Name": "hPUM"
}
]
}
]
This is my logic
public ArrayList<Summary> getHouseHoldRecordsByCase(String country, String projectId, String case) {
ArrayList<Summary> documents= new ArrayList<>();
Summary summary = new Summary();
ArrayList<ItemDetails> details = new ArrayList<>();
COVER cover = dataStoreService.getHouseHoldRecordsByCase(country, projectId, caseNumber);
summary.case = caseNumber;
summary.recordType = "Identification";
summary.country = country;
summary.projectId = projectId;
Field[] fields = hsecover.getClass().getDeclaredFields();
for (Field _f:fields){
try {
String val = PropertyUtils.getProperty(hsecover, _f.getName()).toString();
details.add(new ItemDetails(val, _f.getName(), val, _f.getName()));
} catch (Exception e) {
e.printStackTrace();
}
}
summary.itemDetails = details;
documents.add(summary);
summary = new Summary();
ELIGILITY elig = dataStoreService.getEliByCase(country, projectId, case);
summary.recordType = "Eligibility";
summary.case = case;
summary.country = country;
summary.projectId = projectId;
details = new ArrayList<>();
fields = elig.getClass().getDeclaredFields();
for (Field _f:fields){
try {
String val = PropertyUtils.getProperty(elig, _f.getName()).toString();
details.add(new ItemDetails(val, _f.getName(), val, _f.getName()));
} catch (Exception e) {
e.printStackTrace();
}
}
summary.itemDetails = details;
documents.add(summary);
}
return documents;
}
public COVER getHouseHoldRecordsByCase(String country, String projectId, String case) {
COVER usa = cover_repository.findByCase(case);
return usa;
}
public ELIGILITY getEliByCase(String country, String projectId, String case) {
ELIGILITY usa = eligility_repository.findByCaseNumber(case);
return usa;
}
My ItemDetails model class
public class ItemDetails {
public String ItemValue;
public String Label;
public String ItemValueLabel;
public String Name;
public ItemDetails(String itemValue, String label, String itemValueLabel, String name) {
ItemValue = itemValue;
Label = label;
ItemValueLabel = itemValueLabel;
Name = name;
}
}
My Summary class
public class Summary {
public String country;
public String projectId;
public String case;
public String recordType;
public ArrayList<ItemDetails> itemDetails;
}
The data comes from a database.
How can I set the label names with names that make sense instead of coming as entity names?
You Can use #JsonProperty("different names") on each fields
Or you can use #JsonSetter("different name") on setter method level.
I'm parsing dynamic nested json using gson and Retrofit in Android. I want to exclude null/empty values before I add it to the list.
I've tried the following methods but none of them seem to work:
// retMap.values().removeIf(Objects::isNull);
// Collection<POJOContent> values = retMap.values();
// while (values.remove(null)) {}
//list.removeAll(Arrays.asList(""));
CustomDeserialiser.java
public class CustomDeserializer implements JsonDeserializer<MyContentWrapper> {
private final String abc_key = "abc";
#Override
public MyContentWrapper deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
MyContentWrapper abc = new MyContentWrapper();
JsonObject object = json.getAsJsonObject().getAsJsonObject(abc_key);
List<POJOContent> list = new ArrayList<POJOContent>();
System.out.println("New Data: "+object);
for (Map.Entry<String, JsonElement> set : object.entrySet()) {
System.out.println("LIST " + set);
JsonObject nextObject = object.getAsJsonObject().getAsJsonObject(set.getKey());
Map<String, POJOContent> retMap = new Gson().fromJson(nextObject, new TypeToken<LinkedHashMap<String, POJOContent>>() {
}.getType());
// retMap.values().removeIf(Objects::isNull);
// Collection<POJOContent> values = retMap.values();
// while (values.remove(null)) {}
list.addAll(retMap.values());
//list.removeAll(Arrays.asList(""));
}
abc.abc = list;
return abc;
}
POJOContent.java
public class POJOContent {
#SerializedName("ab")
public String content;
#SerializedName("id")
public String id;
#SerializedName("key")
public String key;
#Override
public String toString() {
return content;
}
//getters and setters
}
MyContentWrapper.java
public class MyContentWrapper {
public List<POJOContent> abc;
}
JSON:
{
"abc": {
"1": {
"1": {
"ab": "some content",
"id": "240",
"key": "value"
},
"2": {
"ab": "some content",
"id": "240",
"key": "value"
},
"3": {
"ab": "some content",
"id": "240",
"key": "value"
}
},
"2": {
"1": {
"ab": "some content",
"id": "241",
"key": "value"
},
"2": {
"ab": "some content",
"id": "241",
"key": "value"
},
"3": {
"ab": "some content",
"id": "241",
"key": "value"
}
},
"3": {
"1": {
"ab": "",
"id": "252",
"key": "value"
},
"2": {
"ab": "some content",
"id": "252",
"key": "value"
},
"3": {
"ab": "",
"id": "252",
"key": "value"
}
}
}
}
Basically, I want to skip the objects whose "ab" value is empty and NOT add them to the list (the other keys are irrelevant if the "ab" value is empty). To clarify, if the parent object has any child object with "ab" key empty value, the child object should be excluded. If the parent object has all children whose "ab" key has empty values, it should exclude the parent object.
Am I missing something? Would appreciate some help.
EDIT:: Expected JSON:
{
"abc": {
"1": {
"1": {
"ab": "some content",
"id": "240",
"key": "value"
},
"2": {
"ab": "some content",
"id": "240",
"key": "value"
},
"3": {
"ab": "some content",
"id": "240",
"key": "value"
}
},
"2": {
"1": {
"ab": "some content",
"id": "241",
"key": "value"
},
"2": {
"ab": "some content",
"id": "241",
"key": "value"
},
"3": {
"ab": "some content",
"id": "241",
"key": "value"
}
},
"3": {
"2": {
"ab": "some content",
"id": "252",
"key": "value"
}
}
}
}
UPDATE 2:
This is the response I'm getting after changing List to Maps:
Callback<MyContentWrapper> myCallback = new Callback<MyContentWrapper>() {
#Override
public void onResponse(Call<MyContentWrapper> call, Response<MyContentWrapper> response) {
if (response.isSuccessful()) {
Log.d("Callback", " Message: " + response.raw());
Log.d("Callback", " Message: " + response.body().abc.values());
still showing empty brackets here --->
//Log.d = Message: [{1=1. some content, 1=2. some content, 1=3. some content}, {}]
} else {
Log.d("Callback", "Code: " + response.code() + " Message: " + response.message());
}
}
#Override
public void onFailure(Call<MyContentWrapper> call, Throwable t) {
t.printStackTrace();
}
};
Just for context, this is the JSON response to above the callback:
{
"abc": {
"1": {
"1": {
"ab": "some content",
"id": "240",
"key": "value"
},
"2": {
"ab": "some content",
"id": "240",
"key": "value"
},
"3": {
"ab": "some content",
"id": "240",
"key": "value"
}
},
"2": {
"1": {
"ab": "",
"id": "241",
"key": "value"
},
"2": {
"ab": "",
"id": "241",
"key": "value"
},
"3": {
"ab": "",
"id": "241",
"key": "value"
}
}
}
}
First of all your MyContentWrapper is wrong. It is not a List according to your JSON. It should be map of maps so something like:
public class MyContentWrapper {
public Map<Integer, Map<Integer, POJOContent>> abc;
}
Now, you could write some complex deserializer for this kind of structure but there is also an another way to do it. Namely, if you declare helper Map like:
#SuppressWarnings("serial")
public class MyMap extends HashMap<Integer, POJOContent> {
#Override
public POJOContent put(Integer key, POJOContent value) {
if(null==value.getContent() || value.getContent().isBlank()) {
return null;
}
// Added only if content = "ab" is not blank.
return super.put(key, value);
}
}
and then the tuned MyContentWrapper:
public class MyContentWrapper {
public Map<Integer, MyMap> abc;
}
Then it is only:
MyContentWrapper mcw = new Gson().fromJson(JSON, MyContentWrapper.class);
Hi guys i have struck with one problem while i am trying to access one api services it is all working fine. But my issue iin processing the response .
I am using retrofit 2.0
Below is my json response for my api
{
"status": 200,
"success": "true",
"data": [
{
"works_node": [
{
"works_items": [
{
"work_id": "number",
"preference": "number",
"Task_created_time": "datetime yyyy-mm-dd h:m:s"
}
]
}
],
"questions_node": [
{
"questions_items": [
{
"q_id": "number",
"work_id": "number",
"question_text": "string",
"preference": "number"
}
]
}
],
"answers_node": [
{
"answers_items": [
{
"a_id": "number",
"q_id": "number",
"answer_text": "string",
"prefernce": "number",
"point": "number",
"is_suggest": "number",
"work_id": "number"
}
]
}
],
"answer_suggestions_node": [
{
"answer_suggestions_items": [
{
"a_id": "number",
"q_id": "number",
"answer_suggestion_text": "string",
"point": "number",
"work_id": "number"
}
]
}
]
}
]
}
Below is the api calling code
public void getWorkTaskConfig(){
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
String DeviceImei=uf.getIMEI();
int userId=db.getUserId();
Call<WorkTaskConfig> call = apiService.getWorkTaskConfig
(new BasicData(new UserInfo(userId),new DeviceInfo(DeviceImei)));
call.enqueue(new Callback<WorkTaskConfig>() {
#Override
public void onResponse(Call<WorkTaskConfig> call, Response<WorkTaskConfig> response) {
try {
int apiStatus= response.body().getStatus();
Boolean apiSuccess=response.body().getSuccess();
if (apiStatus == Constants.RESULT_CODE_OK &&
apiSuccess.equals(Constants.RESULT_SUCCESS_OK)) { //data received successfully
List<Datum> apiAllWorkTaskConfigData=response.body().getData();
List<WorksNode> apiAllWorksNodeData=response.body().getData().getWorksNode(); // im facing
//the problem here ie i am not able to access the getWorksNode() function
//in Datum.java class.
}else{ //while retrieving data something went wrong.
}
} catch (Exception e) { e.printStackTrace(); }
}
#Override
public void onFailure(Call<WorkTaskConfig> call, Throwable t) { }
});
}
WorkTaskConfig.java
public class WorkTaskConfig {
#SerializedName("status")
#Expose
private Integer status;
#SerializedName("success")
#Expose
private Boolean success;
#SerializedName("data")
#Expose
private List<Datum> data = null;
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Boolean getSuccess() {
return success;
}
public void setSuccess(Boolean success) {
this.success = success;
}
public List<Datum> getData() {
return data;
}
public void setData(List<Datum> data) {
this.data = data;
}
}
Datum.java
public class Datum {
#SerializedName("works_node")
#Expose
private List<WorksNode> worksNode = null;
public List<WorksNode> getWorksNode() {
return worksNode;
}
public void setWorksNode(List<WorksNode> worksNode) {
this.worksNode = worksNode;
}
}
Solution
Edit Json structure
Edit POJO class(Datum)
Edit Json Structure
data is an object, not array.
{
"status": 200,
"success": "true",
"data": {
"works_node": [{
"works_items": [{
"work_id": "number",
"preference": "number",
"Task_created_time": "datetime yyyy-mm-dd h:m:s"
}]
}],
"questions_node": [{
"questions_items": [{
"q_id": "number",
"work_id": "number",
"question_text": "string",
"preference": "number"
}]
}],
"answers_node": [{
"answers_items": [{
"a_id": "number",
"q_id": "number",
"answer_text": "string",
"prefernce": "number",
"point": "number",
"is_suggest": "number",
"work_id": "number"
}]
}],
"answer_suggestions_node": [{
"answer_suggestions_items": [{
"a_id": "number",
"q_id": "number",
"answer_suggestion_text": "string",
"point": "number",
"work_id": "number"
}]
}]
}
}
Edit POJO class
go to link below and generate the pojo class again.
http://www.jsonschema2pojo.org/
And Try this.
WorkTaskConfig taskConfig = reponse.body();
List<WorksNode> worksNode = taskConfig.getData().getWorksNode();
List<QuestionsNode> questionsNode = taskConfig.getData().getQuestionsNode();
List<AnswersNode> answersNode = taskConfig.getData().getAnswersNode();
List<AnswerSuggestionsNode> answerSuggestionsNode = taskConfig.getData().getAnswerSuggestionsNode();
Replace all WorkTaskConfig to JsonElement if you are facing some problem .
and Parse manually with Gson like..
String apiAllWorkTaskConfigData = response.body().getData();
WorkTaskConfig mWorkTaskConfig = new Gson.fromJson(apiAllworkTaskConfigData,WorkTaskConfig.class);
I am going to get facebook read_books
The file is in this format:
{
"data": [
{
"id": "270170479804513",
"from": {
"name": "L I",
"id": "1000022"
},
"start_time": "2014-01-22T09:31:00+0000",
"publish_time": "2014-01-22T09:31:00+0000",
"application": {
"name": "Books",
"id": "174275722710475"
},
"data": {
"book": {
"id": "133556360140246",
"url": "https://www.facebook.com/pages/Pride-and-Prejudice/133556360140246",
"type": "books.book",
"title": "Pride and Prejudice"
}
},
"type": "books.reads",
"no_feed_story": false,
"likes": {
"count": 0,
"can_like": true,
"user_likes": false
},
"comments": {
"count": 0,
"can_comment": true,
"comment_order": "chronological"
}
},
{
"id": "270170328",
"from": {
"name": "h",
"id": "100004346894022"
},
"start_time": "2014-01-22T09:29:42+0000",
"publish_time": "2014-01-22T09:29:42+0000",
"application": {
"name": "Books",
"id": "174275722710475"
},
"data": {
"book": {
"id": "104081659627680",
"url": "https://www.facebook.com/pages/Gulistan-of-Sadi/104081659627680",
"type": "books.book",
"title": "Gulistan of Sa'di"
}
},
"type": "books.reads",
"no_feed_story": false,
"likes": {
"count": 0,
"can_like": true,
"user_likes": false
},
"comments": {
"count": 0,
"can_comment": true,
"comment_order": "chronological"
}
}
],
I need books titles and their URL. I run the below code but I get Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to java.lang.String
while ((inputLine = in.readLine()) != null)
{
s = s + inputLine + "\r\n";
if (s == null) {
break;
}
t = t + inputLine + "\r\n";
}
in.close();
t = t.substring(0, t.length() - 2);
System.out.println(t);
Object dataObj =JSONValue.parse(t);
System.out.println(dataObj);
JSONObject dataJson = (JSONObject) dataObj;
JSONArray data = (JSONArray) dataJson.get("data");
for (Object o: data)
{
JSONObject indata= (JSONObject) o;
Object indatafirst=(JSONObjec`enter code here`t).get("0");
String inndata=(String) indatafirst.get("data");
System.out.println("inndata"+inndata);
}}
but it is not true
The problem is with the following line:
String inndata=(String) indatafirst.get("data");
The data field in the JSON is not a String, it's a nested JSON object.
"data": {
"book": {
"id": "104081659627680",
"url": "https://www.facebook.com/pages/Gulistan-of-Sadi/104081659627680",
"type": "books.book",
"title": "Gulistan of Sa'di"
}
}
This explains your ClassCastException.
Instead you should do something like:
JSONObject data = (JSONObject) indatafirst.get("data");
JSONObject book = (JSONObject) data.get("book");
String bookTitle = book.get("title");