I just can not solve this problem. I get the data from the server, save them in shared preferences key = data value = "[.. json].
The structure and type of data can be seen in the screenshot.
How to correctly json in the List <User ..>. I use this code, in which it uses jackson2 library, but it does not work. I'm getting an error
JsonMappingException: Can not deserialize instance of com.example.dmitriysamoilov.filipapp.model.UserContactListModel out of START_ARRAY token
public List<UserContactListModel> getUserLocalContactsData() {
List<UserContactListModel> listModels = new ArrayList<>();
String json = "";
sharedPreferences = context.getSharedPreferences(ReservedName.USER_LOCAL_CONTACTS_DATA,
context.MODE_PRIVATE);
if (sharedPreferences.contains("json")) {
json = sharedPreferences.getString("json", "");
}else return listModels;
ObjectMapper mapper = new ObjectMapper();
try {
// Convert JSON string from file to Object
UserContactListModel l = mapper.readValue(json,UserContactListModel.class);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return listModels;
}
I understand that the logic is not true, but I can not figure this out very long
Since your json is array, try as below
listModels = Arrays.asList(mapper.readValue(json, UserContactListModel[].class));
Giving a short example try to find out your result.
String jsonArray = "[{\"brand\":\"ford\"}, {\"brand\":\"Fiat\"}]";
ObjectMapper objectMapper = new ObjectMapper();
List<Car> cars1 = objectMapper.readValue(jsonArray, new TypeReference<List<Car>>(){});
Here for your code-
public List<UserContactListModel> getUserLocalContactsData() {
List<UserContactListModel> listModels = new ArrayList<>();
String json = "";
sharedPreferences = context.getSharedPreferences(ReservedName.USER_LOCAL_CONTACTS_DATA,
context.MODE_PRIVATE);
if (sharedPreferences.contains("json")) {
json = sharedPreferences.getString("json", "");
}else return listModels;
ObjectMapper mapper = new ObjectMapper();
try {
// Convert JSON string from file to Object
listModels = mapper.readValue(json,new TypeReference<List<UserContactListModel>>(){});
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return listModels;
}
Related
I am using Playframework(scalaVersion 2.12.4) with Java 1.8 and Couchbase(Couchbase java-client 2.4.2). I am fetching UserDetails document and updating the same document in the database.
My code is working in normal scenarios, couldn't test the conflicting edge cases. Hence, not sure whether my code will work or not.
How to handle TemporaryLockFailureException? My current exception handling seems to be wrong.
#Override
public void submitUsersDetails(DashboardRequest request) {
logger.debug("inside submitDashboardDetails");
CompletableFuture.runAsync(() -> {
try {
bucket = cluster.openBucket(config.getString(PctConstants.COUCHBASE_BUCKET_NAME),
config.getString(PctConstants.COUCHBASE_BUCKET_PASSWORD));
String documentID = PctConstants.USER_PROFILE;
JsonDocument retrievedJsonDocument = bucket.getAndLock(documentID, 5);
if (retrievedJsonDocument != null) {
JsonNode json = Json.parse(retrievedJsonDocument.content().toString());
UserDetails userDetails = Json.fromJson(json, UserDetails.class);
// UPDATING userDetails
JsonObject jsonObject = JsonObject.fromJson(Json.toJson(userDetails).toString());
bucket.replace(JsonDocument.create(documentID, jsonObject, retrievedJsonDocument.cas()));
logger.info("Successfully entered record into couchbase");
} else {
logger.error("Fetching User_details unsuccessful");
throw new DataNotFoundException("User_details data not found");
}
} catch (TemporaryLockFailureException e) {
try {
logger.debug("Inside lock failure **************************");
Thread.sleep(5000);
String documentID = PctConstants.USER_PROFILE;
JsonDocument retrievedJsonDocument = bucket.getAndLock(documentID, 5);
if (retrievedJsonDocument != null) {
JsonNode json = Json.parse(retrievedJsonDocument.content().toString());
UserDetails userDetails = Json.fromJson(json, UserDetails.class);
// UPDATING userDetails
JsonObject jsonObject = JsonObject.fromJson(Json.toJson(userDetails).toString());
bucket.replace(JsonDocument.create(documentID, jsonObject, retrievedJsonDocument.cas()));
logger.info("Successfully entered record into couchbase");
submitDashboardDetails(request);
} else {
logger.error("Fetching User_details unsuccessful");
throw new DataNotFoundException("User_details data not found");
}
} catch (InterruptedException e1) {
e1.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
try {
throw e;
} catch (Exception e1) {
e1.printStackTrace();
}
}
}, ec.current()).join();
}
I would like to create a Json structure manually using JsonObject and JsonArrays like the below:
{
"data":[
{
"company_name":"xyz",
"Amount":"$2000",
"Duplicate_amount":"$500"
},
{
"company_name":"abc",
"Amount":"$5000"
},
{
"company_name":"zzz",
"Amount":"$2500",
"Duplicate_amount":"$1000"
}
]
}
The Json above is to be generated based on a checking done on an Arraylist. For example: Arraylist [xyz,abc,zzz,xyz,hhh,zzz]. Now I want to check, if the arraylist contains duplicate elements i.e here "xyz" and "zzz" then in the Json structure, the Duplicate_amount Json object to be added in the Json. Else if no duplicate present then only "company_name" and "amount" to be formed. The whole json format to be formed in this way.
How to do it? I have the logic for finding duplicate elements. But I cannot seem to find the logic for forming the above json based on the checking.
Thank you
Updates
So far I have tried this with checking. But the below code doesn't work and is not forming the appropriate json. What is the solution ?:
JSONObject root_jsonObj = new JSONObject();
JSONArray jsonArr = new JSONArray();
JSONObject sub_jsonobj= new JSONObject();
Object[] st = AppData.customer_arr.toArray();
for (Object s : st) {
//The if-else is the duplicate checking part here
if (AppData.customer_arr.indexOf(s) != AppData.customer_arr.lastIndexOf(s)) {
try {
sub_jsonobj.put("name",AppData.customer_arr.get(counter));
sub_jsonobj.put("dup_amount",AppData.amt_arr.get(counter));
} catch (Exception e) {
e.printStackTrace();
}
}
else{
try {
sub_jsonobj.put("name",AppData.customer_arr.get(counter));
sub_jsonobj.put("amount",AppData.amt_arr.get(counter));
} catch (Exception e) {
e.printStackTrace();
}
}
jsonArr.put(sub_jsonobj);
counter++;
}
try {
root_jsonObj.put("data", jsonArr);
} catch (Exception e) {
e.printStackTrace();
}
You can use this one.
JSONObject obj1 = new JSONObject();
try {
obj1.put("company_name", "xyz");
obj1.put("Amount", "$2000");
obj1.put("Duplicate_amount", "$500");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject obj2 = new JSONObject();
try {
obj2.put("company_name", "xyz");
obj2.put("Amount", "$2000");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray();
jsonArray.put(obj1);
jsonArray.put(obj2);
JSONObject dataObj = new JSONObject();
dataObj.put("Data", jsonArray);
String jsonStr = dataObj.toString();
System.out.println("jsonString: "+jsonStr);
My java code looks something like this:
public class CreateSolr4Doc {
public static void main(String[] args) {
int recordCount = 3;
CreateSolr4Doc instance = new CreateSolr4Doc();
instance.createDummyData(recordCount);
}
private void createDummyData(int recordCount) {
String url = "http://localhost:8983/solr/collection1";
System.out.println(url);
HttpSolrServer solr = new HttpSolrServer(url);
for (int index = 0; index < recordCount; index++) {
for(int j=1;j<=20000;j++)
{
SolrInputDocument doc = new SolrInputDocument();
Date date = new Date();
doc.addField("id","ibsfdjkhfb"+index+j);
doc.addField("mongoid", "4eebb9db43d7391c16509153");
doc.addField("agency","AFP");
doc.addField("title","Masked men loot cash, cellphones"+(index+1));
doc.addField("story",(index+1) + "PATNA: Giving a damn to");
doc.addField("mimetype","TEXT");
doc.addField("subject","The criminals first reached the office-cum")
doc.addField("coverage","patna");
doc.addField("isSyndicated",1);
doc.addField("createdDate",org.apache.commons.lang.time.DateUtils.addDays(date, -(index+101)));
doc.addField("expiryDate","2061-12-17T03:06:13Z");
doc.addField("language","en");
doc.addField("version","1.0");
doc.addField("ingestionDate","2011-12-16T21:36:28.296Z");
doc.addField("ingestionDate_index","2011-12-17T03:06:00Z");
System.out.println("Inserting document"+" "+(j)+" "+(index+1));
try {
solr.add(doc);
} catch (SolrServerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
UpdateResponse response = solr.commit();
System.out.println(response);
} catch (SolrServerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
When I insert data I get an error message something like this:-
Inserting document 1 1
Exception in thread "main" org.apache.solr.common.SolrException: ERROR: [doc=ibsfdjkhfb01] unknown field 'mongoid'
The error is encountered when i add fields in the document.
I don't know how to proceed.
Based on the error message, it appears that you have a field that is not in your schema. Try adding mongoid to your schema.xml and see if that helps.
I see an old method from a colleague of deserializing json object in java where the json is taken as string deserialized and passed the values in an array. What I dont understand about this code is why for every field try and catch method is added and why can't we have a single try and catch because all catch do the same thing of catching the json exception and assigning responseArray[0] to value 1.
Here is the code:
String[] responseArray = new String[4];
Arrays.fill(responseArray, "");
try {
final JSONObject response1 = new JSONObject(response);
try{
responseArray[0] = response1.getJSONObject("body")
.getJSONObject("responseStatus").getString("estado");
}
catch (JSONException e) {
responseArray[0] = "1";
e.printStackTrace();
}
if(!responseArray[0].equalsIgnoreCase("0")){
try{
responseArray[1] = response1.getJSONObject("body")
.getJSONObject("responseStatus")
.getString("codigoRespuesta");
}
catch (JSONException e) {
responseArray[0] = "1";
e.printStackTrace();
}
try{
responseArray[2] = response1.getJSONObject("body")
.getJSONObject("responseStatus")
.getString("descripcionRespuesta");
}
catch (JSONException e) {
responseArray[0] = "1";
e.printStackTrace();
}
}
try{
responseArray[3] = response1.getJSONObject("body")
.getJSONObject("responseData").getLong("esValido")+"";
}
catch (JSONException e) {
responseArray[0] = "1";
e.printStackTrace();
}
} catch (JSONException e) {
responseArray[0] = "1";
e.printStackTrace();
}
return responseArray;
There is no explicit need to add try and catch blocks to every ".getJSONObject" methods.
There are two ways by which you can use exception handling.
1. try-catch blocks. Single try & catch block would work fine as well.
2. Let the method throws JSONException as a replacement to try and catch blocks.
Checked exceptions (like the one in your case) are checked at compile time, and so you need to handle them using either of the two ways
Exception handling reference link
hi i want to parse my downloaded json file that stored in the SDCard directory ,
i don't know how can i do that !
im google a lot but i can only find somethings like : BuffredReader , InputFileStream , ...
please help me !
here is part of my code but it have the problem i attached in the image :
File GroupsJsonFileAdress = new File(Enviroments.getExternalStorageDirectory() + "FOLDER/G.json");
try {
ObjectInputStream groupsInJson = new ObjectInputStream(new FileInputStream(GroupsJsonFileAdress));
JSONObject jsonObject = (JSONObject)groupsInJson.readObject();
String DATABASE_VERSION = jsonObject.getString("DBVersion");
JSONArray groupsArray = jsonObject.getJSONArray("Groups");
for (int i = 0; i < groupsArray.length(); i++) {
JSONObject groupJsonObjectReader = groupsArray.getJSONObject(i);
int id= groupJsonObjectReader.getInt("Id");
String gTitle = groupJsonObjectReader.getString("title");
Group loaderG = new Group();
loaderG.GroupId = id;
loaderG.Title = gTitle;
Log.i("INFO", loaderG.Title);
groupsClasses.add(loaderG);
}
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
and here is the error i got :
http://i.stack.imgur.com/lQ3YN.jpg
Create a model that matches your Json architecture and then parse it using GSON librarie ;)
Easiest way to do it so far for me :)