Split jsonarray data into multiple list using array value - java

I want to split an ArrayList according to the existing data, Like as
category etc.
I try nested for loop and add them into list.but It's not working.
String url = "http://27.147.169.230/UpSkillService/UpSkillsService.svc/" + "GetCNCCourseDefByorg/" + 1 +"/" +1;
Ion.with(getApplicationContext())
.load("GET",url)
.setBodyParameter("","")
.asString()
.setCallback(new FutureCallback<String>() {
#Override
public void onCompleted(Exception e, String result) {
Log.d("Result",result);
try {
JSONObject obj =new JSONObject(result);
JSONArray jsonArray = obj.getJSONArray("GetCNCCourseDefByorgResult");
//Arrays.sort(new JSONArray[]{jsonArray});
if(obj.isNull("GetCNCCourseDefByorgResult"))
{
Toast.makeText(getApplicationContext(),"No Course Found",Toast.LENGTH_SHORT).show();
}
else if (!obj.equals(null)) {
String cata="";
Log.d("Resul3", jsonArray.toString());
for (int i = 0; i < jsonArray.length(); i++) {
final CourseCatagory catagoryModel = new CourseCatagory();
JSONObject course = jsonArray.getJSONObject(i);
CourseList courselist = new CourseList();
if(cata!=course.getString("CategoryName"))
{
Log.d("Catagory",cata);
catagoryModel.setCategoryName(course.getString("CategoryName"));
arrayListcatagory.add(catagoryModel);
for (int j=0;j<jsonArray.length();j++)
{
JSONObject cat1 = jsonArray.getJSONObject(j);
cata=cat1.getString("CategoryName");
Log.d("cat",cata);
if(cat1.getString("CategoryName")==course.getString("CategoryName"))
{
courselist.setCourseName(cat1.getString("CourseName"));
courselist.setCourseCode(cat1.getString("CourseCode"));
courselist.setWishFlag(cat1.getInt("WishFlag"));
Log.d("Course",cat1.getString("CourseName"));
arrayListcourse.add(courselist);
}
else {
}
}
}
catagoryModel.setCourseList(arrayListcourse);
}
adapter.notifyDataSetChanged();
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
});
}
`
I want as catagory, under catagory course shown which match catagory name.
Accounting>Introduction Accounting,Advance accounting
Finance>Introduction Finance

You can Use HashMap<String,ArrayList<CategoryDetails>> to resolve your Problem.
First Create CategoryDetails POJO class
class CategoryDetails {
private courseName;
private courseCode;
private wishFlag;
//make setter and getter methods for above fields.
}
Then use category Name as key in HashMap to differentiate as mentioned in first line of my answer.
Map<String,ArrayList<CategoryDetails>> listCategory = new HashMap<String,ArrayList<CategoryDetails>>;

Related

How to print the json to listview included two data?

I want to display two data on listview through the json input. All the code are alter from internet which I got error. I have not clear logic to understand the meaning of the code. Please give me advice and alter my code.
private void displayArrayList(String jsonStr){
String[] from = {"eventName", "date"};
int[] to = {R.id.eventName, R.id.date};
SimpleAdapter simpleAdapter = new SimpleAdapter (
getActivity(),convertToWordArrayList(jsonStr), R.layout.listview_layout,from,to);
simpleAdapter.notifyDataSetChanged();
listView.setAdapter(simpleAdapter);
}
private ArrayList<HashMap<String, ActivityInfo>> convertToWordArrayList(String jsonStr){
JSONObject jsonObject ;
ArrayList<HashMap<String, ActivityInfo>> arrayList = new ArrayList<HashMap<String, ActivityInfo>>();
try{
jsonObject = new JSONObject(jsonStr);
JSONArray jsonArray=jsonObject.getJSONArray("article");
for (int i=0;i<jsonArray.length();i++){
JSONObject jsonObjRow=jsonArray.getJSONObject(i);
ActivityInfo activityInfo =new ActivityInfo();
activityInfo.eventName = jsonObjRow.getString("eventName");
activityInfo.date = jsonObjRow.getString("date");
HashMap<String, String> map= new HashMap<String, ActivityInfo>();
map.put("eventName", activityInfo.eventName );
map.put("date", activityInfo.date);
JSONArray jsonArray2=jsonObjRow.getJSONArray("content");
for (int j=0;j<jsonArray2.length();j++) {
JSONObject jsonObjRow2 = jsonArray2.getJSONObject(j);
activityInfo.review = jsonObjRow2.getString("review");
}
arrayList.add(activityInfo);
}
}catch (JSONException e){
e.printStackTrace();
}
return arrayList;
}
ActivityInfo class (using the serializable to got the result )
public class ActivityInfo implements Serializable {
String eventName;
String date ;
public void setEventName(String eventName){
this.eventName =eventName ;
}
public String toString(){
return this.eventName;
}
}
Json Response is no problem
{
"article":[
{
"activityId":"5c5d8addd404c",
"eventName":"running",
"date":"2019-02-08",
"content":[
{
"review":"you there"
},
{
"review":"please go away"
},
]
},
{
"activityId":"5c5d8b318df62",
"eventName":"basketball",
"date":"2019-02-13",
"content":[
{
"review":"confirm again"
}
]
},
{
"activityId":"5c5d8b9308018",
"eventName":"playing",
"date":"2019-02-16",
"content":[
{
"review":"provid of you"
}
]
}
]
}
I totally do it like this:
public class menuCreation()
{
public string Category { get; set; }
public string ItemName { get; set; }
public string Price { get; set; }
public string FileName { get; set; }
public menuCreation[] Arr { get; set; }
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string json = (reader.ReadToEnd());
List<menuCreation> items = JsonConvert.DeserializeObject<List<menuCreation>>(json);
Arr = items.ToArray();
}
menuCreation mc = new menuCreation();
foreach (var item in mc.Arr)
{
PictureBox pb = new PictureBox();
pb.Tag = item.ItemName;
pb.Name = item.Price;
}
You can see, I reach itemName with class object.So, you can add listview with this method.
This is your Model Class..
ActivityInfo.java
public class ActivityInfo implements Serializable {
String eventName;
String date;
public void setEventName(String eventName){
this.eventName = eventName ;
}
public String getEventName(){
return this.eventName;
}
public void setDate(String date){
this.date = date;
}
public String getDate(){
return date;
}
}
This will be your final errorfree code..
private void displayArrayList(String jsonStr){
String[] from = {"eventName", "date"};
int[] to = {R.id.eventName, R.id.date};
SimpleAdapter simpleAdapter = new SimpleAdapter (
getActivity(),convertToWordArrayList(jsonStr), R.layout.listview_layout,from,to);
simpleAdapter.notifyDataSetChanged();
listView.setAdapter(simpleAdapter);
}
private ArrayList<HashMap<String,String>> convertToWordArrayList(String jsonStr){
JSONObject jsonObject;
ArrayList<HashMap<String,String>> arrayList = new ArrayList();
try{
jsonObject = new JSONObject(jsonStr);
JSONArray jsonArray=jsonObject.getJSONArray("article");
for (int i=0;i<jsonArray.length();i++){
JSONObject jsonObjRow=jsonArray.getJSONObject(i);
HashMap<String,String> hashMap=new HashMap<>();//create a hashmap to store the data in key value pair
hashMap.put("eventName",jsonObjRow.getString("eventName"));
hashMap.put("date",jsonObjRow.getString("date"));
JSONArray jsonArray2=jsonObjRow.getJSONArray("content");
/*If you want to get Content Reviews from Json, you need to make another attributes like Content in ActivityInfo Class*/
arrayList.add(hashmap);
}
}catch (JSONException e){
e.printStackTrace();
}
return arrayList;
}

storing an JSON array in java code array in android

I want to store the json array sent by php code in java array in android. My php code is working perfectly fine but in the app I get name: as the output. I want to display the names in the texview for checking purpose. Also I want to work with the namesby accessing them one by one.
Php code:
echo json_encode(array("result"=>$result));
Java code:
public class Salary {
public static final String DATA_URL1 = "http://********.com/name.php?salary=";
public static final String KEY_name = "name";
public static final String JSON_ARRAY1 = "result";
}
This is a method of my Name.java
private void showJSON(String response) {
String name = "";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Salary.JSON_ARRAY1);
for (int i = 0; i < result.length(); i++) {
JSONObject collegeData = result.getJSONObject(i);
name = collegeData.getString(Salary.KEY_name);
}
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult1.setText("Name:\t" + name);
}
Use GSON Library
ArrayList<Salary> salaryArrayList = new ArrayList<>();
try {
salaryArrayList = new Gson().fromJson(response, new TypeToken<Salary>() {}.getType());
} catch (JsonSyntaxException e) {
e.printStackTrace();
}
Then use salaryArrayList to get values.
Download GSON jar from this link

Hashmap clear values

I have this code. When i clear ArrayList, values in HashMap clear too. How can i save data?
public class Stations extends AppCompatActivity {
public static Map<String, ArrayList<String>> cities = new HashMap<>();
...
public void parseFrom() {
cities.clear();
ArrayList<String> citiesList = new ArrayList<>();
try {
JSONObject jObject = new JSONObject(loadJSON());
JSONArray jArray = jObject.getJSONArray("citiesFrom");
String countryTitle = null;
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
if ((countryTitle != null) && (!countryTitle.equals(jsonObject.getString("countryTitle")))) {
cities.put(countryTitle, citiesList);
citiesList.clear();
}
countryTitle = jsonObject.getString("countryTitle");
citiesList.add(jsonObject.getString("cityTitle"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
When I use citiesList.clear();all values are clearing, but keys still "alive".
This is because they have the same reference in memory.
Try doing this:
cities.put(countryTitle, new ArrayList<String>(citiesList));
But, if what you really want is to remove it from the hashmap, you'll have to call cities.remove(countryTitle) instead of only clearing the array of cities.

Extract JSON Keynames in Java

I want to extract JSON structure (only keyNames structure) by preserving the hierarchy (parent child relationship); I don't want values from the JSON yet.
I am new to Java and have been tying to achieve this using Jackson , but with no success.
Any direction on this will be much appreciated.
I created a static inner class for you by using JSONObject (http://www.json.org/javadoc/org/json/JSONObject.html)
public static class KeyNode {
private String name;
private ArrayList<KeyNode> children;
public KeyNode(String name) {
this.name = name;
this.children = new ArrayList<KeyNode>();
}
public void addChild(KeyNode child) {
this.children.add(child);
}
public static void parseJsonToKeys(KeyNode node, JSONObject json) throws JSONException {
Iterator<?> keys = json.keys();
while (keys.hasNext()) {
String name = (String) keys.next();
KeyNode child = new KeyNode(name);
node.addChild(child);
if (json.optJSONObject(name) != null) {
parseJsonToKeys(child, json.getJSONObject(name));
} else if (json.optJSONArray(name) != null) {
JSONArray array = json.getJSONArray(name);
for (int i = 0; i < array.length(); i++) {
try {
array.getJSONObject(i);
parseJsonToKeys(child, json.getJSONObject(name));
} catch (JSONException e) {
// this is ok
}
}
}
}
}
public static void exampleCodeUsage() {
try {
JSONObject json = new JSONObject("your json");
KeyNode keyHierarchy = new KeyNode("root");
parseJsonToKeys(keyHierarchy, json);
} catch (JSONException e) {
// your json is not formatted correctly
}
}
}
JSONParser parser = parser;
Object obj = parser.parse(new FileReader(FileName.Json));
JSONObject jobj = (JSONObject) obj;
obj.keys()
The method will give you the list of all keys in JSONObject

How to modify values of JsonObject / JsonArray directly?

Once i have parsed a JSON String into a GSON provided JsonObject class, (assume that i do not wish to parse it into any meaningful data objects, but strictly want to use JsonObject), how am i able to modify a field / value of a key directly?
I don't see an API that may help me.
https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/JsonObject.html
Strangely, the answer is to keep adding back the property. I was half expecting a setter method. :S
System.out.println("Before: " + obj.get("DebugLogId")); // original "02352"
obj.addProperty("DebugLogId", "YYY");
System.out.println("After: " + obj.get("DebugLogId")); // now "YYY"
This works for modifying childkey value using JSONObject.
import used is
import org.json.JSONObject;
ex json:(convert json file to string while giving as input)
{
"parentkey1": "name",
"parentkey2": {
"childkey": "test"
},
}
Code
JSONObject jObject = new JSONObject(String jsoninputfileasstring);
jObject.getJSONObject("parentkey2").put("childkey","data1");
System.out.println(jObject);
output:
{
"parentkey1": "name",
"parentkey2": {
"childkey": "data1"
},
}
Since 2.3 version of Gson library the JsonArray class have a 'set' method.
Here's an simple example:
JsonArray array = new JsonArray();
array.add(new JsonPrimitive("Red"));
array.add(new JsonPrimitive("Green"));
array.add(new JsonPrimitive("Blue"));
array.remove(2);
array.set(0, new JsonPrimitive("Yelow"));
Another approach would be to deserialize into a java.util.Map, and then just modify the Java Map as wanted. This separates the Java-side data handling from the data transport mechanism (JSON), which is how I prefer to organize my code: using JSON for data transport, not as a replacement data structure.
It's actually all in the documentation.
JSONObject and JSONArray can both be used to replace the standard data structure.
To implement a setter simply call a remove(String name) before a put(String name, Object value).
Here's an simple example:
public class BasicDB {
private JSONObject jData = new JSONObject;
public BasicDB(String username, String tagline) {
try {
jData.put("username", username);
jData.put("tagline" , tagline);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getUsername () {
String ret = null;
try {
ret = jData.getString("username");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public void setUsername (String username) {
try {
jData.remove("username");
jData.put("username" , username);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String getTagline () {
String ret = null;
try {
ret = jData.getString("tagline");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ret;
}
public static JSONObject convertFileToJSON(String fileName, String username, List<String> list)
throws FileNotFoundException, IOException, org.json.simple.parser.ParseException {
JSONObject json = new JSONObject();
String jsonStr = new String(Files.readAllBytes(Paths.get(fileName)));
json = new JSONObject(jsonStr);
System.out.println(json);
JSONArray jsonArray = json.getJSONArray("users");
JSONArray finalJsonArray = new JSONArray();
/**
* Get User form setNewUser method
*/
//finalJsonArray.put(setNewUserPreference());
boolean has = true;
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
finalJsonArray.put(jsonObject);
String username2 = jsonObject.getString("userName");
if (username2.equals(username)) {
has = true;
}
System.out.println("user name are :" + username2);
JSONObject jsonObject2 = jsonObject.getJSONObject("languages");
String eng = jsonObject2.getString("Eng");
String fin = jsonObject2.getString("Fin");
String ger = jsonObject2.getString("Ger");
jsonObject2.put("Eng", "ChangeEnglishValueCheckForLongValue");
System.out.println(" Eng : " + eng + " Fin " + fin + " ger : " + ger);
}
System.out.println("Final JSON Array \n" + json);
jsonArray.put(setNewUserPreference());
return json;
}

Categories