Store JSON array value in HashMap and remove duplicate - java

I have a JSON response which look something like this( its different from user to user)
{
"success": true, "data":
[
{
"mandatory_tag": "My Company",
"id": "topic_1408946825893148"
},
{
"mandatory_tag": "Partners",
"id": "topic_1408946942491149",
},
{
"mandatory_tag": "Industry",
"id": "topic_1408946996510150",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1409210454810358",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1408947133657152"
},
{
"mandatory_tag": "Competitors",
"id": "topic_1408947071457151",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1409210621754362",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1409210704390363",
},
{
"mandatory_tag": "Competitors",
"id": "topic_1409210794791364"
}
]
}
I am parsing it and trying to store in HashMap, but the key value is duplicating. Can anyone suggest me how can i store all id with same mandatory_tag in one array?
I am new to this so please consider..thanks
try
{
JSONObject jsonMain = new JSONObject(jsonString);
JSONArray dataArray = jsonMain.getJSONArray("data");
for(int i = 0; i < dataArray.length(); i++)
{
JSONObject tagObject = dataArray.getJSONObject(i);
String mandatory_tag = tagObject.getString("mandatory_tag");
String id = tagObject.getString("id");
List<String> arrayID = new ArrayList<String>();
if(myMap.containsKey(mandatory_tag))
{
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
} else
{
List<String> newArrayID = new ArrayList<String>();
newArrayID.add(id);
myMap.put(mandatory_tag, newArrayID);
}
}
And well i got stuck at this now..any good logic please..

A hashmap allows you to store key-value items. I would suggest the HashMap be of type <String,List<String>> so allowing you to store items with the same mandatory_tag in the same list under 1 key.
For example
HashMap<String,List<String>> myMap = new HashMap<String,List<String>>();
if (myMap.containsKey(mandatory_tag)) {
List<String> values = myMap.get(mandatory_tag);
if (values!=null) {
values.add(id)
} else {
values = new List<String>();
values.add(id);
}
}
Update
As I wrote in my comment below, the except you added has an error
List<String> arrayID = new ArrayList<String>();
if(myMap.containsKey(mandatory_tag))
{
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
}
What you are doing here is, if the map already contains the key you are replacing the value associated with the key with a new list which contains only 1 value. What you need to do is update the list of already existing values. Check the code below and make sure you understand the problem. These are fundamentals of programming and you need to understand the logic of what you're doing to advance.
//Somewhere you have declared your HashMap
HashMap<String,List<String>> myMap = new HashMap<String,List<String>>();
//then we continue with your excerpt
try {
JSONObject jsonMain = new JSONObject(jsonString);
JSONArray dataArray = jsonMain.getJSONArray("data");
for(int i = 0; i < dataArray.length(); i++) {
JSONObject tagObject = dataArray.getJSONObject(i);
String mandatory_tag = tagObject.getString("mandatory_tag");
String id = tagObject.getString("id");
if(myMap.containsKey(mandatory_tag)) {
List<String> arrayID = myMap.get(mandatory_tag);
arrayID.add(id);
} else {
List<String> newArrayID = new ArrayList<String>();
newArrayID.add(id);
myMap.put(mandatory_tag, newArrayID);
}
}

Create a POJO called TagValues(or whatver name you would like) with variables mandatory_tag,id and then and create an ArrayList<TagValues> in which you can store all the objects.

Thanks for your response, but with help of you guys, i got the solution
`HashMap<String,List<String>> myMap = new HashMap<String,List<String>>();
for(int i = 0; i < dataArray.length(); i++)
{
JSONObject tagObject = dataArray.getJSONObject(i);
String mandatory_tag = tagObject.getString("mandatory_tag");
String id = tagObject.getString("id");
if(myMap.isEmpty())
{
arrayID = new ArrayList<String>();
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
}
else if(myMap.containsKey(mandatory_tag))
{
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
}
else
{
arrayID = new ArrayList<String>();
arrayID.add(id);
myMap.put(mandatory_tag, arrayID);
}
}`

In those cases, I'd like to use a custom HashMap:
public MMap getData() {
MMap result = new MMap();
JSONArray array = getJSONArrayFromTotalJSON();
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
String mtag = obj.getString(MANDATORY_TAG);
String id = obj.getString(ID);
result.put(mtag, id);
}
return result;
}
public class MMap extends HashMap<String, List<String>> {
public void put(String key, String value) {
if (!this.containsKey(key))
this.put(key, new ArrayList<String>());
this.get(key).add(value);
}
}

Related

Using loop with JSONObject to create nested JSON in JAVA [duplicate]

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 2 years ago.
I try to create the following JSON:
{
"metadata": {
"0": {
"attribute": "technology",
"value": "Ceramics",
"mandatory": "rule"
},
"1": {
"attribute": "color",
"value": "Green",
"mandatory": "rule"
},
"2": {
"attribute": "material",
"value": "Nylon",
"mandatory": "rule"
}
}
}
metadataReq is type JSONObject and it contains the values above
JSONObject obj = new JSONObject();
JSONObject index = new JSONObject();
JSONArray keys = metadataReq.names();
for (int i = 0; i < metadataReq.length (); i++) {
String key = keys.getString (i);
String val = metadataReq.getString (key);
String j = Integer.toString(i);
obj.put("attribute", key);
obj.put("value", val);
obj.put("mandatory", "rule");
index.put(j, obj);
jsonRecipe.put("metadata", index);
}
My script for some reason cause the last object (index #2), to show similar values on the other two objects (#0 and #1)
Using the for loop, how to create it correctly?
The problem in the above code is JSONObject obj = new JSONObject(); initialised only one but you need to create inside the loop.
This code gives the expected output as you want:
public static void main(String[] args) throws JSONException {
JSONObject index = new JSONObject();
JSONObject jsonRecipe = new JSONObject();
JSONObject metadataReq = new JSONObject();
metadataReq.put("technology","Ceramics");
metadataReq.put("material","Nylon");
metadataReq.put("color","Green");
JSONArray keys = metadataReq.names();
for (int i = 0; i < metadataReq.length (); i++) {
String key = keys.getString (i);
String val = metadataReq.getString (key);
String j = Integer.toString(i);
JSONObject obj = new JSONObject();
obj.put("attribute", key);
obj.put("value", val);
obj.put("mandatory", "rule");
index.put(j, obj);
jsonRecipe.put("metadata", index);
}
System.out.println(jsonRecipe);
}
You only created 1 object and inserted it 3 times, as opposed to creating 3 distinct objects.

How do I properly parse this JSON?

I have a big JSON file that contains Countries, States and Cities. The JSON looks like this:
{
"Countries":[
{
"CountryName":"India",
"States":[
{
"StateName":"Maharashtra",
"Cities":[
"Pune",
"Nagpur",
"Mumbai"
]
},
{
"StateName":"Kerala",
"Cities":[
"Kochi",
"Munnar"
]
}
]
},
{
"CountryName":"Australia",
"States":[
{
"StateName":"Aukland",
"Cities":[
"GlenField",
"Henderson",
"MilFord"
]
},
{
"StateName":"Melbourne",
"Cities":[
"Melbourne",
"South Oakleigh"
]
}
]
}
]
}
I have an activity in my app that requires the user to select a country and upon selecting a country I want to get all the states of that country as an array list. And when a specific state is selected, I want to get all the cities of that state as an array list.
I am able to get a list of all Countries using this method:
public void loadCountries(String parent, String child, ArrayList<String> listValue)
{
try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj.getJSONArray(parent);;
ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> m_li;
// listValue = new ArrayList<>();
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
Log.d("Details-->", jo_inside.getString(child));
listValue.add(jo_inside.getString(child));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("Contries.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
Then, in the onCreate method, using this line gives me all the countries in an array list
loadCountries("Countries", "CountryName", countries);
Since this is my first time working with a JSON file in AndroidStudio/Java, I have no idea what to do to get the states and the cities. Any help is greatly appreciated.
You could use GSON library. Just create corresponding java object which will reflect json structure and do like here:
MyClass data = new Gson().fromJson(json, MyClass.class);
Respect for trying to do this yourself, but we live in the age of the API. Check out Google's GSON library, it parses JSON to java objects, and java objects to JSON. It's one of the most useful APIs out there. https://github.com/google/gson
Try this:
Map<String, Map<String, Map<Integer, String>>> data = new HashMap<>();
try {
JSONObject object = new JSONObject(loadJSONFromAsset());
JSONArray countries = object.getJSONArray("Countries");
for (int i = 0; i < countries.length(); i++) {
JSONObject state = countries.getJSONObject(i);
JSONArray statesList = state.getJSONArray("States");
String countryName = countries.getJSONObject(i).getString("CountryName");
for (int j = 0; j < statesList.length(); j++) {
JSONObject city = statesList.getJSONObject(j);
JSONArray citiesList = city.getJSONArray("Cities");
String stateName = city.getString("StateName");
Map<String, Map<Integer, String>> stateHashMap = new HashMap<>();
for (int k = 0; k < citiesList.length(); k++) {
cityList.add(citiesList.getString(k));
String cityName = citiesList.getString(k);
Map<Integer, String> cityHashmap = new HashMap<>();
cityHashmap.put(k, cityName);
stateHashMap.put(stateName, cityHashmap);
data.put(countryName, stateHashMap);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}

How to get values from json String

I have a json string string from which I want to get the values. It is in key pair form so I want the values for each key.
I tried to get the values but I am not getting it.
Json String is like :
{
"document": {
"xmlns:xsi": "http:\/\/www.w3.org\/2001\/XMLSchema-instance",
"xsi:schemaLocation": "http:\/\/ocrsdk.com\/schema\/recognizeard-1.0.xsd http:\/\/ocrsdk.com\/schema\/recognized-1.0.xsd",
"xmlns": "http:\/\/ocrsdk.com\/schema\/recognize-1.0.xsd",
"businessCard": {
"imageRotation": "noRotation",
"field":
[{
"type": "Name",
"value": "Rafcev B. Agnrwal"
}, {
"type": "Company",
"value": "VJ>"
}, {
"type": "Text",
"value": "Dr. Rafcev B. Agnrwal\nMOB 0324%\nun\n) AOM*. founts. sso\nVJ>\nT"
}]
}
}
}
I want to get values of "Name", "Address", "Company" etc.
I tried to get like this:
JSONArray array;
if(mIntent.getStringExtra("jsonString") != null) {
Log.d("json", mIntent.getStringExtra("jsonString"));
try {
JSONObject object = new JSONObject(mIntent.getStringExtra("jsonString"));
array = object.getJSONArray("field");
for (int i = 0; i < array.length(); i++) {
JSONObject subObject1 = array.getJSONObject(i);
edt_FirstName.setText(object.getString("Name"));
}
} catch (JSONException e) {
}
Can anyone help me out please? Thank you..
EDIT:
I tried to check values like this:
for (int i = 0; i < array.length(); i++) {
JSONObject subObject1 = array.getJSONObject(0);
String type = subObject1.getString("type");
String value = subObject1.getString("value");
if (type.equals("Name")) {
edt_FirstName.setText(value);
}
if(type.equals("Address"))
{
edt_address.setText(value);
}
if(type.equals("Company"))
{
edt_company.setText(value);
}
if(type.equals("Mobile"))
{
edt_Mobile.setText(value);
}
}
I want to get all the values from field array and set to the text view, but I am getting only the Name value and not the others.
Also I could get one field as twice like Mobile I can get twice, so I want to combine both the Mobile values and show it.
So your json object is as follow:
{
"document": {
"xmlns:xsi": "http:\/\/www.w3.org\/2001\/XMLSchema-instance",
"xsi:schemaLocation": "http:\/\/ocrsdk.com\/schema\/recognizeard-1.0.xsd http:\/\/ocrsdk.com\/schema\/recognized-1.0.xsd",
"xmlns": "http:\/\/ocrsdk.com\/schema\/recognize-1.0.xsd",
"businessCard": {
"imageRotation": "noRotation",
"field":
[{
"type": "Name",
"value": "Rafcev B. Agnrwal"
}, {
"type": "Company",
"value": "VJ>"
}, {
"type": "Text",
"value": "Dr. Rafcev B. Agnrwal\nMOB 0324%\nun\n) AOM*. founts. sso\nVJ>\nT"
}]
}
}
}
You first need to get "document" as JSONObject and then get "businessCard" as JSONObject and then you can get "field" as JSONArray:
if(mIntent.getStringExtra("jsonString") != null) {
Log.d("json", mIntent.getStringExtra("jsonString"));
try {
JSONObject object = new JSONObject(mIntent.getStringExtra("jsonString"));
JSONArray array = object.getJSONObject("document").getJSONObject("businessCard").getJSONArray("field");
for (int i = 0; i < array.length(); i++) {
JSONObject subObject = array.getJSONObject(i);
String type = subObject.getString("type");
String value = subObject.getString("value");
if (type.equals("Name")) {
String prevValue = edt_FirstName.getText();
edt_FirstName.setText((TextUtils.isEmpty(prevValue) ? "" : prevValue + ",") + value);
}
}
} catch (JSONException e) { }
}
Try this code, Hope it will help you.
try
{
JSONObject jsonObject = new JSONObject();
JSONObject documentObject = jsonObject.getJSONObject("document");
JSONObject businessCardObject = documentObject.getJSONObject("businessCard");
String imgRotation = businessCardObject.getString("imageRotation");
JSONArray array = businessCardObject.getJSONArray("field");
for (int i = 0; i < array.length() ; i++)
{
JSONObject arrObj = array.getJSONObject(i);
String type = arrObj.getString("type");
String value = arrObj.getString("value");
Log.e(TAG, "type=="+type);
Log.e(TAG, "value=="+value);
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
here is code
private void convertJsonToDto(String jsonNewString) {
JSONObject jsonObj = new JSONObject(jsonNewString);
String RecordLocator = (String) jsonObj.get("obj");
String FirstName = (String) jsonObj.getJSONObject("Customer").get("FirstName");
JSONArray array = new JSONObject(jsonNewString).getJSONArray("Array");
JSONObject jsonObject = array.getJSONObject(0);
String str = jsonObject.getString("object");
}

my json parser for jsonarry just get the first element

i have parser function that parse json array and return arrays that i use it in a list adapter and then the adapter is used by a recyclerview .it's giving me the actual length but only the first element of the arrays is filled while the others return NULL
that is my code
public void parsee_item() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
final JSONArray userss = jsonObject.getJSONArray(JSON_ARRAY);
item_id = new String[userss.length()];
item_owner = new String[userss.length()];
item_images = new String[userss.length()];
item_names = new String[userss.length()];
item_price = new String[userss.length()];
item_place = new String[userss.length()];
JSONObject jo = null;
for (int i = 0; i < userss.length();i++) {
jo = userss.getJSONObject(i);
Log.d("alrsp", jo.toString());
item_id[i] = jo.getString(KEY_ID);
item_owner[i] = jo.getString(KEY_OWNER);
item_images[i] = jo.getString(KEY_IMAGE);
item_names[i] = jo.getString(KEY_NAME);
item_price[i] = jo.getString(KEY_PRICE);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
the json is
{
"result": [{
"item_id": "10",
"owner": "user",
"item_type_id": "1",
"url1": "http:\/\/localhost:8080\/market\/items\/14.1.png",
"name": "jc",
"price": "76"
}, {
"item_id": "12",
"owner": "user",
"item_type_id": "1",
"url1": " http:\/\/localhost:8080\/market\/items\/14.1.png",
"name": "nzbsbsb",
"price": "0"
}, {
"item_id": "13",
"owner": "user",
"item_type_id": "1",
"url1": " http:\/\/localhost:8080\/market\/items\/14.1.png",
"name": "uygf",
"price": "0"
}]
}
and this screenshot of the list
enter image description here
it's not suggested parsing json yourself ,use a Json Parse Util such as Gson or fastJson instead .
I used your code, debug, and found values are updated their is no error with JSON paring, So check your recycler view adapter code or share it
Replace this line
jo = userss.getJSONObject(4);
with this
jo = userss.getJSONObject(i);
JSONObject jo = null;
for (int i = 0; i < userss.length();i++) {
jo = userss.getJSONObject(i);
Log.d("alrsp", jo.toString());
item_id[i] = jo.getString(KEY_ID);
item_owner[i] = jo.getString(KEY_OWNER);
item_images[i] = jo.getString(KEY_IMAGE);
item_names[i] = jo.getString(KEY_NAME);
item_price[i] = jo.getString(KEY_PRICE);
item_place[i] = jo.getString("place");
}
the problem with ur code is you use hardcode value 4
jo = userss.getJSONObject(4);
insted of this use
jo = userss.getJSONObject(i);
at each and every time you are parsing the index 4 jsonObject information
public void parsee_item() {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(json);
final JSONArray userss = jsonObject.getJSONArray(JSON_ARRAY);
item_id = new String[userss.length()];
item_owner = new String[userss.length()];
item_images = new String[userss.length()];
item_names = new String[userss.length()];
item_price = new String[userss.length()];
item_place = new String[userss.length()];
JSONObject jo = null;
for (int i = 0; i < userss.length();) {
jo = userss.getJSONObject(i);
Log.d("alrsp", jo.toString());
item_id[i] = jo.getString(KEY_ID);
item_owner[i] = jo.getString(KEY_OWNER);
item_images[i] = jo.getString(KEY_IMAGE);
item_names[i] = jo.getString(KEY_NAME);
item_price[i] = jo.getString(KEY_PRICE);
item_place[i] = jo.getString("place");
i++;
}
} catch (JSONException e) {
e.printStackTrace();
}
}
if you use this type of parsing it may lead to null pointer exception
You can parse above JSON as follows
private void jsonParse(String response) throws JSONException {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("result");
if (jsonArray != null && jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
if (object != null) {
String itemId = object.getString("item_id");
String owner = object.getString("owner");
String item_type_id = object.getString("item_type_id");
String url1 = object.getString("url1");
String name = object.getString("name");
String price = object.getString("price");
}
}
}
}
i was receiving a parameter that wasn't being sent by the jsonarray
item_place[i] = jo.getString("place")

Java- Processing Json array based on keys

I'm getting this string (from webservice) into a JSONArray,
[{
"textinput": [{
"position": 0,
"dependency": "no",
"id": 0,
"Itype": "textinput"
}, {
"position": 2,
"dependency": "no",
"id": 1,
"Itype": "textinput"
}]
}, {
"textarea": [{
"position": 1,
"type": "textarea",
"dependency": "no",
"id": 0
}]
}]
I need to sort the array by ascending order based on key-"position"
I am using org.json library, the below code is the one so far the code i used
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonList = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonList.add(jsonArray.getJSONObject(i));
}
Collections.sort( jsonList, new Comparator<JSONObject>() {
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get("position");
valB = (String) b.get("position");
}
catch (JSONException e) {
//do something
}
return valA.compareTo(valB);
}
});
for (int i = 0; i < jsonArray.length(); i++) {
sortedJsonArray.put(jsonList.get(i));
}
AALso tried other links in the site.
please help
Try TreeMap, it will automatically sort the array for you. All you have to do is make "position" the Key of TreeMap and JSONObject the value. The treemap will arrange the values in ascending order of the keys.And then you can retrieve the JSONObject values from the treemap.
private TreeMap<Integer,JSONObject> sortedarray = new TreeMap<Integer,JONObject>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
sortedarray.put(Integer.parseInt(jsonArray.getJSONObject(i).get("position")+""),jsonArray.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}
}
Now if you want it to be a jsonArray only..
JSONArray sortedJsonArray = new JSONArray();
for(int x = 0; x<sortedarray.size();x++)
{
//assuming that positions you get in JSON are always complete like 1,2,3,4,....,10,...,100.
sortedJsonArray.put(sortedarray.get(x));
//assuming that positions you get in JSON are not always complete like 1,3,4,..,10,13,...,100.( misses a few numbers in between like 2 and 11 in this case)
sortedJsonArray.put(sortedarray.get(Integer.parseInt(advanceplay.get(advanceplay.keySet().toArray()[i]))));
}

Categories