Remove duplicated in base Unique JSONObjects in JSONArray - java

How Remove duplicated JSONObjects in JSONArray java android
I have this code and I do not know how to remove duplicates, according to the duplicate value of number and time of arrays strings objects, but but I do not know how to do it, I'm a bit confused with arrays
[
{
"isChecked": true,
"name": "weber",
"number": "+1912123456789",
"time": "28 nov., 08:06 PM",
"type": "all"
},
{
"isChecked": true,
"name": "weber",
"number": "+1912123456789",
"time": "28 nov., 08:06 PM",
"type": "all"
},
//Duplicatedhowremovethisifnumberisequalandtime{
"isChecked": true,
"name": "weber",
"number": "+1912123456789",
"time": "28 nov., 08:07 PM",
"type": "all"
}
]
I would appreciate your help

JSON parser by default allows duplicates so there is no direct way to remove the duplicates. However, there are ways to deal with this. You can validate JSON against schema.
If using Jackson, here is the setting which will help you to detect duplicates:
final ObjectMapper mapper = new ObjectMapper();
mapper.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);

You need to use set data structure. Set store unique objects. If you have custom objects, you need to override equals method and hash code method.

I got the solution, i shared you
String getloglist = sp.getString(Constant.LOG, "");
ArrayList<String> listdata = new ArrayList<String>();
try {
// Load the data from json
JSONArray jsonArraylogs= new JSONArray(getloglist);
if (jsonArraylogs != null) {
for (int i=0;i<jsonArraylogs.length();i++){
listdata.add(jsonArraylogs.getString(i));
//Toast.makeText(context, ""+listdata+"", Toast.LENGTH_SHORT).show();
}
}
} catch (JSONException e) {
Toast.makeText(context, "error", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
//Toast.makeText(context, ""+listdata+"", Toast.LENGTH_SHORT).show();
ArrayList<String> values=new ArrayList<String>();
HashSet<String> hashSet = new HashSet<String>();
hashSet.addAll(listdata);
listdata.clear();
listdata.addAll(hashSet);
Toast.makeText(context, ""+listdata+"", Toast.LENGTH_SHORT).show();

Related

Get keys from multiple JSON objects

I have a JSON object that contains undetermined pattern and I need to get all keys of the json object and the sub-objects.
Here's an example of a JSON file:
{
"users": {
"address": [
{
"rue": "ruetest",
"postal": 1111
},
{
"rue": "ruetest",
"postal": 2222
}
],
"type": "string",
"user": [
{
"argent": 122,
"id": 1,
"nom": "user1",
"prenom": "last1"
},
{
"argent": 200,
"id": 2,
"nom": "user2",
"prenom": "last2"
},
{
"argent": 1205,
"id": 3,
"nom": "user3",
"prenom": "last3"
}
]
}
}
and I need to have output like this:
[users,type,address,user,argent,id,nom,prenom] or something like this
I don't think there's really a built-in way to do this, but you could achieve your goal by making a function that does it. Something like (in pseudocode):
public Set getJsonKeys(JSON json) {
Set s = new Set();
for (Entry e : json.entrySet()) {
s.add(e.key);
if (e.value instanceof JSON) s.addAll(getJsonKeys(e.value));
}
return s;
}
I chose a Set rather than List to prevent duplicate entries. If you want to include keys of lists just add a check if e.value is a list and if so, iterate over elements and add getJsonKeys(element) for all elements.
Have you tried the Genson Java Collections mode?
It would give you easy generic access to arbitrary JSON files in java.
If you use the fastjson framework, I think you can use the following code to get all the keys:
JSONObject jsonObject = new JSONObject(jsonData);
Iterator keys = jsonObject.keys();
while (keys.hasNext()){
String key = String.valueOf(keys.next());
}

How would I access this key within a JSON object in Java?

I've been having some problems iterating through a JSON object in Java.
Specifically, I'd like to save each value for "name" to the string array "nameList". I've looked up how to do this, and I haven't found a way for this situation.
String[] nameList = new String[]{};
{
"data": {
"Narray": {
"0":
{
"_id": "001",
"name": "studio",
"date": "02141992"
},
"1":
{
"_id": "002",
"name": "venue",
"date": "09041999"
}
}
}
Ideally you'd want Narray to be an actual JSON array, enclosed in [], with each element being another object, containing the property you need, like this:
{
"Narray": [
{
"_id": "001",
"name": "studio",
"date": "02141992"
},
{
"_id": "002",
"name": "venue",
"date": "09041999"
}
]
}
Then you can use jackson to decode the JSON string into a POJO structure. Once you have the objects, you can iterate over the array and retrieve the property you need into a list.
I assume that you only want to save each value of name into a String[] (string array), so you don't need to deserialize the JSON string to POJO, just use basic API to achieve what you want as follows:
BTW, your JSON string is invalid, you miss a right bracket.
ObjectMapper mapper = new ObjectMapper();
JsonNode nArray = mapper.readTree(jsonStr).get("data").get("Narray");
String[] nameList = new String[nArray.size()];
for (int i = 0; i < nArray.size(); i++) {
nameList[i] = nArray.get(String.valueOf(i)).get("name").asText();
}
System.out.println(Arrays.toString(nameList));
Console output:
[studio, venue]

parse json object from json array in java using com.fasterxml.jackson.databind.JsonNode;

I am trying to parse some json which is a groupd of objects within an array. I am not fluent with java and having a hard time figuring out how to do this.
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
JsonNode messageNode = mapper.readTree(post);
if (!messageNode.isArray()){
try {
throw new Exception("INVALID JSON");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
ArrayList<String> listObjects = null;
JsonParser parser = mapper.getFactory().createParser(post);
the json format:
{
"data": [
{
"id": "897569693587466_897626706915098",
"from": {
"id": "1809583315",
"name": "Lena Cann Jordan"
},
"message": "Amen.",
"can_remove": false,
"created_time": "2014-11-11T22:41:11+0000",
"like_count": 0,
"user_likes": false
},
{
"id": "897569693587466_897627376915031",
"from": {
"id": "1776031725",
"name": "Kyla Munford"
},
"message": "Tell me what my God can't do!!!",
"can_remove": false,
"created_time": "2014-11-11T22:42:51+0000",
"like_count": 0,
"user_likes": false
},
{
"id": "897569693587466_897631636914605",
"from": {
"id": "100000106496788",
"name": "Sarah Barklow Tyson"
},
"message": "That's bc God is awesome!! He can give or take away!! \ud83d\ude4f\u2795",
"can_remove": false,
"created_time": "2014-11-11T22:49:46+0000",
"like_count": 0,
"user_likes": false
}
],
"paging": {
"cursors": {
"after": "WTI5dGJXVnVkRjlqZFhKemIzSTZPRGszTmpVMk1USXdNalExTkRrd09qRTBNVFUzTkRrNU5qTTZOREE9",
"before": "WTI5dGJXVnVkRjlqZFhKemIzSTZPRGszTmpJMk56QTJPVEUxTURrNE9qRTBNVFUzTkRVMk56RTZNelU9"
},
"previous": "some link"
}
}
This is the json from the facebook graph api. I also need to extract the cursors and links below so would they also appear as one of the objects.
Appreciate advice.
Thanks
I think the real question is what you are trying to achieve? You are already parsing JSON into a tree model (JsonNode), and from that point on you can traverse content freely, using methods get, path and at (which uses JSON Pointer expression).
Or, as suggested by Samwise above, could consider modeling Java classes with same structure as JSON, so that you would have even easier time accessing data as regular Java objects. If so, you'd parse it simply by:
Graph graph = mapper.readValue(post);
Data d = graph.getData().get(0); // for first entry in "data" List

Parsing Json in Android and set it in a ListView

In my android project, I have the string text which got the following data:
[
{
"admin": true,
"created_at": "2012-10-16T07:26:49Z",
"email": "asdf#gmail.com",
"id": 28,
"language": "fr",
"name": "Marc",
"profile_pic_content_type": null,
"profile_pic_file_name": null,
"profile_pic_file_size": null,
"profile_pic_updated_at": null,
"provider": null
},
{
"admin": false,
"created_at": "2013-04-02T18:47:36Z",
"email": "asdf2#gmail.com",
"id": 263,
"language": "en",
"name": "Marcus",
"profile_pic_content_type": null,
"profile_pic_file_name": null,
"profile_pic_file_size": null,
"profile_pic_updated_at": null,
"provider": null
}
]
I converted it into a json object thanks to this:
JSONObject jsonObj = new JSONObject(text);
I want to parse that Json object, and setting it inside a ListView, but even with the official documentation I can't succeed in doing so.
After parsing, I want to keep only the first part of the array, and delete every field excepting the email, language and name, to get this in the end:
[
{
"email": "asdf#gmail.com",
"language": "fr",
"name": "Marc"
}
]
You're dealing with a JSONArray - the [ ] - that contains two separate JSONObject. The way you extract values from this structure is simply to go piece by piece, first getting the nested objects from the array and then extracting their internal values. You can then repackage it as you wish. For example:
int numObject = jsonArray.length();
JSONArray repackArray = new JSONArray();
for(int i = 0; i < numObject; i++){
JSONObject nested = jsonArray.getJsonObject(i);
//get values you need
String email = nested.getString("email");
String language = nested.getString("language");
String name = nested.getString("name");
//add values to new object
JSONObject repack = new JSONObject();
repack.put("email", email);
repack.put("language", language);
repack.name("name", name);
//add to new array
repackArray.put(repack);
}
Alternatively if put doesn't work for you, you can always create your own String in JSON format and then simply create a new JSONObject using that string as an argument in the constructor. I assumed you were working with a JSONArray in the above example. If you're starting with a JSONObject the process is the same. Just get the JSONArray out of the object first before unpacking.

Parse simple JSON

I have a trouble to parse this piece of JSON
{
"00408C88A2E6": {
"id": "00408C88A2E6",
"name": "pippo"},
"00408C91188B": {
"id": "00408C91188B",
"name": "pluto"
},
"00408C944B99": {
"id": "00408C944B99",
"name": "minni"
},
"00408C944BA0": {
"id": "00408C944BA0",
"name": "topolino"
}
I need to get all the key "id" and "name", I tried with an iterator but I was able to retrive just the first dicts (00408C88A2E6,00408C91188B...), could anyone give me any hint?
Thank you
Edit:
I'm using org.json and to parse this I tried in this way
JSONObject jsonChannels = getHttpJson(url_user_cam);
ArrayList<String> al = new ArrayList<String>();
Log.i(LOG_TAG, jsonChannels.toString());
try{
Iterator<String> iterator = jsonChannels.keys();
while (iterator.hasNext() ){
al.add(iterator.next());
}
}catch(Exception e){
Log.e(LOG_TAG, e.toString());
}
with this piece of code my intent is to get the first dict ("00408C88A2E6") after make it I need to access to "id" and "name" element, hwo can i do it?
As pointed in the comments, it looks like your JSON is incomplete. Maybe a pasting error ?
Do you do it manually or do you use a library ?
Have you tried using the "official" Java JSON package ?

Categories

Resources