Connect two HashMap Values - java

I've got this JSON string:
String json = "{\"countries\":{\"2\":\"China\",\"3\":\"Russia \",\"4\":\"USA\"},\"capitals\":{\"2\":Beijing,\"4\":null,\"3\":Moscow}}";
I converted string to HashMap, using this:
HashMap<String,Object> map = new Gson().fromJson(json, new TypeToken<HashMap<String, Object>>(){}.getType());
System.out.println(map.get("countries")+"#####"+map.get("capitals"));
And now my output is:
{2=China, 3=Russia , 4=USA}#####{2=Beijing, 4=null, 3=Moscow}
I would like to connect this values by numbers. I want to create two ArrayList like this:
A)- [China,Russia,USA]
B)- [Beijing,Moscow,null]
How can i do it?

First, you need to cast map.get("label") to LinkedTreeMap<Integer, String>, then create new ArrayList with it's values
String json = "{\"countries\":{\"2\":\"China\",\"3\":\"Russia \",\"4\":\"USA\"},\"capitals\":{\"2\":Beijing,\"4\":null,\"3\":Moscow}}";
HashMap<String,TreeMap<Integer, String>> map = new Gson().fromJson(json, new TypeToken<HashMap<String, TreeMap<Integer, String>>>(){}.getType());
ArrayList<String> countries = new ArrayList<>(map.get("countries").values());
System.out.println(countries);
ArrayList<String> capitals = new ArrayList<>(map.get("capitals").values());
System.out.println(capitals);

You can iterate over the country keyset to fill the capital array:
List<String> countries = new ArrayList<>(countriesMap.values());
List<String> capitals = new ArrayList<>();
for (String countryKey : countriesMap.keySet()) {
capitals.add(capitalsMap.get(countryKey));
}

Related

Parse JSON in java (custom)

I have a JSON array in the following format:
[["1234","OS","01/31/2023","02/01/2023","First Day"],["1245","OS","01/23/2023","01/24/2023","Last Day"],["3411","OS","09/21/2022","09/21/2022","Second Day"]]
In Java, I would like to parse this array and store data in the following format:
String[] firstElements = ["1234" , "1245", "3411"];
String[] secondElements = ["OS", "OS", "OS"];
String[] thirdElements = ["01/31/2023", "01/23/2023", "09/21/2022"];
String[] fourthElements = ["02/01/2023", "01/24/2023", "09/21/2022"];
String[] fifthElements = ["First Day", "Last Day", "Second Day"];
Is this possible? How can I achieve this?
String jsonArray = "[[\"1234\",\"OS\",\"01/31/2023\",\"02/01/2023\",\"First Day\"],[\"1245\",\"OS\",\"01/23/2023\",\"01/24/2023\",\"Last Day\"],[\"3411\",\"OS\",\"09/21/2022\",\"09/21/2022\",\"Second Day\"]]";
JsonArray array = Json.createReader(new StringReader(jsonArray)).readArray();
List<String> firstElements = new ArrayList<>();
List<String> secondElements = new ArrayList<>();
List<String> thirdElements = new ArrayList<>();
List<String> fourthElements = new ArrayList<>();
List<String> fifthElements = new ArrayList<>();
array.forEach( value -> {
JsonArray innerArray = value.asJsonArray();
firstElements.add(innerArray.getString(0));
secondElements.add(innerArray.getString(1));
thirdElements.add(innerArray.getString(2));
fourthElements.add(innerArray.getString(3));
fifthElements.add(innerArray.getString(4));
)};
If you want something more generic you can use a List<List<String>>
String jsonArray = "[[\"1234\",\"OS\",\"01/31/2023\",\"02/01/2023\",\"First Day\"],[\"1245\",\"OS\",\"01/23/2023\",\"01/24/2023\",\"Last Day\"],[\"3411\",\"OS\",\"09/21/2022\",\"09/21/2022\",\"Second Day\"]]";
JsonArray array = Json.createReader(new StringReader(jsonArray)).readArray();
List<List<String>> elements = new ArrayList<>();
array.forEach( value -> {
JsonArray innerArray = value.asJsonArray();
List<String> subElements = new ArrayList<>();
for (int i = 0; i < innerArray.size(); i++) {
subElements.add(innerArray.getString(i));
}
elements.add(subElements);
});
There are a few solutions to parsing JSON from Java, like GSON, though if the data format you are working with is simple enough and you don't have to parse all kinds of JSON, you might as well parse it by yourself.

how to convert linkedhashmap to inverted commas except one array value

this is my linkedhashmap
LinkedHashMap<String, Object> jsonOrderedMap = new LinkedHashMap<String, Object>();
jsonOrderedMap = {MessageName=HAPPY DIWALI, MessageID =M001, ListofVehicleID =["KA 01-A-1234","KA-01-A-567"]}
I want result to be in
{"MessageName":"HAPPY DIWALI","MessageID ":"M001","ListofVehicleID ":["KA 01-A-1234","KA-01-A-567"]}
am using
Gson gson = new Gson();
String json = gson.toJson(jsonOrderedMap, LinkedHashMap.class);
to convert but am getting result as
{"MessageName":"HAPPY DIWALI","MessageID ":"M001","ListofVehicleID ":"[\"KA 01-A-1234\",\"KA-01-A-567\"]"}
with array inverted commas and slashes inside the array

Comparing two ArrayList using Gson?

I am trying to compare two ArrayList< Map< String, Object>> objects but the problem is that I need to compare them in different app sessions. So I am saving the first ArrayList in SharedPreferences after converting it to String using Gson. Then I query the string in next session to compare it. I tried converting it back to ArrayList then comparing it with the list generated during the new session. Also tried converting the new list into json and then comparing both texts. But the result is same. Below is the relevant code:
Declaration:
ArrayList<Map<String, Object>> tweetMapArray = new ArrayList<>();
Then in some method :
List<twitter4j.Status> statuses = twitter.getUserTimeline(params[0], new Paging(1, 200));
tweetMapArray.clear(); // I am also reusing it
for (twitter4j.Status status : statuses) {
Map<String, Object> valuesToPutInMarker = new HashMap<>();
valuesToPutInMarker.put("id", status.getId());
valuesToPutInMarker.put("status", status.getText());
tweetMapArray.add(valuesToPutInMarker);
}
Now saving tweetMapArray in SharedPreferences:
String jsonStr = gson.toJson(tweetMapArray);
editor = configData.edit();
editor.putString("tweetData", jsonStr);
editor.apply();
Querying data:
private boolean seeIfTheDataIsNew() {
String dataFromSharedPreferences = configData.getString("tweetData", null);
Type collectionType2 = new TypeToken<ArrayList<Map<String, Object>>>() {
}.getType();
ArrayList<Map<String, Object>> oldTweets = gson.fromJson(dataFromSharedPreferences, collectionType2);
String jsonStr = gson.toJson(tweetMapArray);
return jsonStr.equalsIgnoreCase(dataFromSharedPreferences);
// OR
return !(oldTweets.containsAll(tweetMapArray) && tweetMapArray.containsAll(oldTweets));
}
Here, both methods in last two lines return true. In the testing sample, they should return false.

Putting JSON values into Hashmap

I have JSON value like below,
{ "emp_id": 1017,
"emp_name": "karthik Y",
"emp_designation": "Manager",
"department": "JavaJson",
"salary": 30000,
"direct_reports":
[
"Nataraj G",
"Kalyan",
"Mahitha"
]
}
HashMap < String, String[] >input1 = new HashMap < String, String[] >();
input1.put("empid","1017");
input1.put("emp_name","karthik");
input1.put("emp_designation","manager");
input1.put("salary","30000");
now I want to add next array that is direct_report to put as next key and value(entire array shoud be come one key and value). Someone please help out.
Hashmap is a key/value storage, where keys are unique. You can convert your JSON to string and then store it as a value to the hashmap. For example something like below:
public static void main(String[] args) {
String json = "{ \"emp_id\": 1017,"
+ "\"emp_name\": \"karthik Y\","
+ "\"emp_designation\": \"Manager\","
+ "\"department\": \"JavaJson\","
+ "\"salary\": 30000,"
+ "\"direct_reports\": ["
+ "\"Nataraj G\","
+ "\"Kalyan\","
+ "\"Mahitha\"]}";
HashMap<String, String> jsonStore = new HashMap<String, String>();
jsonStore.put("myJson", json);
System.out.println(jsonStore.get("myJson"));
}
You need can also use the 'org.json' library to
Create JSON object manually
Convert existing JSONObject to String representation
Convert JSON string to JSONObject
You can also have the following solution:
JSONObject jsonObject = new JSONObject();
jsonObject.put("empt_id", 1017);
jsonObject.put("emp_name", "karthik");
HashMap<String, JSONObject> jsonObjectStore = new HashMap<String, JSONObject>();
jsonObjectStore.put("myJsonObject", jsonObject);
HashMap<JSONObject, String> jsonObjectStore2 = new HashMap<JSONObject, String>();
jsonObjectStore2.put(jsonObject, "myJson");
Make sure that you download the org.json jar file and put it in your classpath to be able to use the JSONObject. You can download the jar from here.
In order to put each of those values into map as single key/value entry. You have mentioned it yourself, it should work without any problem. See below methods:
Method 1
Everything in Java is Object, String inherits Object, String[] inherits object. You can have the following solution:
HashMap<String, Object> myObjectStore4 = new HashMap<String, Object>();
String[] directReports4 = new String[]{"Natraj G", "Kalyan", "Mahitha"};
myObjectStore4.put("emp_id", new String("123"));
myObjectStore4.put("emp_name", new String("Raf"));
// others ....
myObjectStore4.put("directReports", directReports4);
Method 2
To store the fields as key/value and if you can afford converting the array to String (which represents all array elements comma separated then use this method).
HashMap<String, String> myObjectStoreTwo = new HashMap<String, String>();
String[] directReports2 = new String[]{"Natraj G", "Kalyan", "Mahitha"};
myObjectStoreTwo.put("emp_id", "123");
myObjectStoreTwo.put("emp_name", "Raf");
myObjectStoreTwo.put("salary", "222");
//Converts array to comma separated String
myObjectStoreTwo.put("directReports",Arrays.toString(directReports2));
Method 3
In the expense of having Hash Map to store String key and Array value. You have to put other elements as array too.
HashMap<String, String[]> myObjectStore3 = new HashMap<String, String[]>();
String[] directReports3 = new String[]{"Natraj G", "Kalyan", "Mahitha"};
myObjectStore3.put("emp_id", new String[]{123 + ""});
myObjectStore3.put("salary", new String[]{32312 + ""});
myObjectStore3.put("directReports", directReports3);
Use a jackson ObjectMapper. Try if this works
String json = "{....}"
HashMap<String,Object> mappedVals = new ObjectMapper().readValue(
json ,
new TypeReference<HashMap<String,Object>>() {
});

Put Hashmap into Arraylist<HashMap>

I'm new at android. I trying to get the data from Database and put it into HashMap. But I got a little problem here. I got an error when I try to put the data that I get.
I put a comment on the error line in my code. You can check it below
Here's my class
private static final String TAG_ITEM_NAME = "item_name";
// Hashmap for ListView
ArrayList<HashMap<String, String>> searchlist;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
searchlist = new ArrayList<HashMap<String, String>>();
Intent search = getIntent();
String searchResult = search.getStringExtra("TAG_SEARCH");
DatabaseHandler db = new DatabaseHandler(
List <AllItem> allItems = new ArrayList<AllItem>();
allItems = db.getAllSearchResult(searchResult);
HashMap<String, AllItem> all_Items = new HashMap<String, AllItem>();
for(AllItem cn : allItems) {
String item_name = cn.getItem_name();
//AllItem item_name = all_Items.put(cn.getItem_name(), cn);
all_Items.put(TAG_ITEM_NAME,item_name); // I got error here
}
searchlist.add(all_Items);
ListAdapter adapter = new SimpleAdapter(
Search.this, searchlist,
R.layout.searchlayout, new String[] {TAG_ITEM_NAME},
new int[] { R.id.category_name}
);
// Assign adapter to ListView
listview.setAdapter(adapter);
}
The error said The Method put(String, Allitem) int type Hashmap<String,Allitem> is not applicable for the argument (String, String)
How to fix this error? Thanks before :D
all_items takes a String and an AllItem, but you are placing two Strings into it in this line:
// TAG_ITEM_NAME is a String and item_name is also a String
all_Items.put(TAG_ITEM_NAME,item_name);
You try to put in the map as a value string but you map expect as a value AllItem, so you must modify your code in this way:
for(AllItem cn : allItems) {
String item_name = cn.getItem_name();
all_Items.put(item_name , cn );
}
This code will add your class object to the map with the key which equals to your object name.
all_Items is defined as a hashmap to contain <String, AllItem> key value pairs as defined here:
HashMap<String, AllItem> all_Items = new HashMap<String, AllItem>();
but you are trying to push <String,String> key value pair into your all_Items hashmap :
all_Items.put(TAG_ITEM_NAME,item_name); // I got error here
It seems you want to push the AllItem object against its item_name, which can be done as:
all_Items.put(item_name, cn);
Your HashMap is as follows:
HashMap<String, AllItem> all_Items = new HashMap<String, AllItem>();
This means it has String keys and AllItem values. You can put a AllItem object inside this HashMap.
When you write
all_Items.put(TAG_ITEM_NAME,item_name); // I got error here
you are putting a String inside the HashMap hence it is giving error.
You should be doing:
all_Items.put(TAG_ITEM_NAME,cn);
Your hashmap is <String, Allitem>. While you try to put <String, String> in it.
all_Items.put(TAG_ITEM_NAME, item_name);
should be changed to
all_Items.put(TAG_ITEM_NAME, cn);
Hope you got the difference.
I dont see connection in the code but using the given information, your error probably is related to your searchlist variable in your code.
change this:
ArrayList<HashMap<String, String>> searchlist;
to this:
ArrayList<HashMap<String, AllItem>> searchlist;
it's because you declared HashMap<String, AllItem> and you try to putall_Items.put(TAG_ITEM_NAME,item_name); which would probably be HashMap<String, String>().

Categories