W/System.err: org.json.JSONException: Value Responsemodel$Banner#b494bac at 0 of type java.lang.String cannot be converted to JSONObject
output:
[Responsemodel$Banner#e5af3c3, Responsemodel$Banner#ed16440, Responsemodel$Banner#5335f79, Responsemodel$Banner#e8cb4be, Responsemodel$Banner#9ef091f]
Getting from SharedPreferences
String getbanner = preferences.getString(Constants.banner_list, null);
Log.i("banner_str", getbanner);
if (getbanner != null) {
JSONArray jsonArray2 = new JSONArray(getbanner);
Log.i("Sharedpref1", jsonArray2.toString());
if (banner_list != null) {
banner_list.clear();
Log.i("Sharedpref2", jsonArray2.toString());
for (int x = 0; x < jsonArray2.length(); x++) {
String object = jsonArray2.getJSONObject(x).getString("imgUrl");
Log.i("bid", object);
HashMap<String, String> map = new HashMap<>();
map.put("imgUrl", object);
banner_list.add(map);
}
}
}
} catch (NullPointerException | JSONException e1) {
e1.printStackTrace();
}
Banner_adapter adapter1 = new Banner_adapter(banner_list);
snapHelper.attachToRecyclerView(recyclerView);
recyclerView.setAdapter(adapter1);
adapter1.notifyDataSetChanged();
Saved in SharedPreferences
getbalres_dto model = response.body(); SharedPreferences.Editor editor = preferences.edit();
editor.putString(Constants.currentBalance, model.getMOBILEAPPLICATION().getCurrentBalance())
.putString(Constants.outletName, model.getMOBILEAPPLICATION().getOutletName())
.putString(Constants.name, model.getMOBILEAPPLICATION().getName())
.putString(Constants.news, model.getMOBILEAPPLICATION().getNews())
.putString(Constants.banner_list, model.getMOBILEAPPLICATION().getBanner().toString())
.putString(Constants.instaurl, model.getMOBILEAPPLICATION().getInstagramUrl())
.putString(Constants.fburl, model.getMOBILEAPPLICATION().getFacebookUrl())
.putString(Constants.youtubeurl, model.getMOBILEAPPLICATION().getYoutubeUrl())
.putString(Constants.twitterurl, model.getMOBILEAPPLICATION().getTwitterUrl())
.putString(Constants.aepsBalance, model.getMOBILEAPPLICATION().getAepsBalance())
.putString(Constants.cartItem, model.getMOBILEAPPLICATION().getCartItem())
.commit();
Java PoJO class
public class getbalres_dto {
#SerializedName("MOBILE_APPLICATION")
#Expose
private MOBILEAPPLICATION mOBILEAPPLICATION;
public MOBILEAPPLICATION getMOBILEAPPLICATION() {
return mOBILEAPPLICATION;
}
public void setMOBILEAPPLICATION(MOBILEAPPLICATION mOBILEAPPLICATION) {
this.mOBILEAPPLICATION = mOBILEAPPLICATION;
}
public class MOBILEAPPLICATION {
#SerializedName("response")
#Expose
private String response;
#SerializedName("Message")
#Expose
private String message;
#SerializedName("news")
#Expose
private String news;
#SerializedName("banner")
#Expose
private JsonArray banner;
#SerializedName("name")
#Expose
private String name;
#SerializedName("outletName")
#Expose
private String outletName;
#SerializedName("currentBalance")
#Expose
private String currentBalance;
#SerializedName("aepsBalance")
#Expose
private String aepsBalance;
#SerializedName("activationAmount")
#Expose
private String activationAmount;
#SerializedName("transactionAmount")
#Expose
private String transactionAmount;
#SerializedName("totalAmount")
#Expose
private String totalAmount;
#SerializedName("isPaid")
#Expose
private String isPaid;
#SerializedName("rentalType")
#Expose
private String rentalType;
#SerializedName("instagramUrl")
#Expose
private String instagramUrl;
#SerializedName("twitterUrl")
#Expose
private String twitterUrl;
#SerializedName("facebookUrl")
#Expose
private String facebookUrl;
#SerializedName("youtubeUrl")
#Expose
private String youtubeUrl;
#SerializedName("cartItem")
#Expose
private String cartItem;
public String getAepsBalance() {
return aepsBalance;
}
public void setAepsBalance(String aepsBalance) {
this.aepsBalance = aepsBalance;
}
public String getInstagramUrl() {
return instagramUrl;
}
public void setInstagramUrl(String instagramUrl) {
this.instagramUrl = instagramUrl;
}
public String getTwitterUrl() {
return twitterUrl;
}
public void setTwitterUrl(String twitterUrl) {
this.twitterUrl = twitterUrl;
}
public String getFacebookUrl() {
return facebookUrl;
}
public void setFacebookUrl(String facebookUrl) {
this.facebookUrl = facebookUrl;
}
public String getYoutubeUrl() {
return youtubeUrl;
}
public void setYoutubeUrl(String youtubeUrl) {
this.youtubeUrl = youtubeUrl;
}
public String getRentalType() {
return rentalType;
}
public void setRentalType(String rentalType) {
this.rentalType = rentalType;
}
public String getIsPaid() {
return isPaid;
}
public void setIsPaid(String isPaid) {
this.isPaid = isPaid;
}
public String getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(String totalAmount) {
this.totalAmount = totalAmount;
}
public String getTransactionAmount() {
return transactionAmount;
}
public void setTransactionAmount(String transactionAmount) {
this.transactionAmount = transactionAmount;
}
public String getActivationAmount() {
return activationAmount;
}
public void setActivationAmount(String activationAmount) {
this.activationAmount = activationAmount;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getNews() {
return news;
}
public void setNews(String news) {
this.news = news;
}
public JsonArray getBanner() {
return banner;
}
public void setBanner(JsonArray banner) {
this.banner = banner;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOutletName() {
return outletName;
}
public void setOutletName(String outletName) {
this.outletName = outletName;
}
public String getCartItem() {
return cartItem;
}
public void setCartItem(String cartItem) {
this.cartItem = cartItem;
}
public String getCurrentBalance() {
return currentBalance;
}
public void setCurrentBalance(String currentBalance) {
this.currentBalance = currentBalance;
}
}}
Getting From SharedPreference
String getbanner = preferences.getString(Constants.banner_list, null);
Gson gson = new Gson();
Log.i("bannerdata__", getbanner);
try {
if (getbanner.isEmpty() || getbanner==null || getbanner.equalsIgnoreCase(null)) {
Log.i("bannerdata__", "empty......");
} else {
Type type = new TypeToken<List<String>>() {
}.getType();
List<String> data = gson.fromJson(getbanner, type);
for (String imgstr : data) {
Log.i("bannerdata_2", imgstr);
HashMap<String, String> map = new HashMap<>();
map.put("imgUrl", imgstr);
banner_list.add(map);
}
Banner_adapter adapter1 = new Banner_adapter(banner_list);
snapHelper.attachToRecyclerView(recyclerView);
recyclerView.setAdapter(adapter1);
adapter1.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
Add data in SharedPreference
final ArrayList<String> arrPackage = new ArrayList<>();
try {
JSONArray jsonArray2 = new JSONArray(getbalmodel.getMOBILEAPPLICATION().getBanner().toString());
if (banner_list != null) {
banner_list.clear();
}
for (int x = 0; x < jsonArray2.length(); x++) {
String bid = jsonArray2.getJSONObject(x).getString("imgUrl");
arrPackage.add(bid);
Gson gson = new Gson();
String json = gson.toJson(arrPackage);
editor.putString(Constants.banner_list, json);
Log.i("imageurl", bid);
HashMap<String, String> map = new HashMap<>();
map.put("imgUrl", bid);
banner_list.add(map);
}
editor.commit();
} catch (JSONException | NullPointerException e1) {
e1.printStackTrace();
}
I Follow below link
how to write code for Json Array Inside Json Array as Category and subcategory with android
But it's cant help for me.
in this link i'll use #Kuldip Kulkerni answer and i'll get data but it's come in to DESC order.
How to i Arrange Main Category and Subcategory and Show in my Recyclerview
What i tried see below codes:
final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
url, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
try {
JSONArray jArray = response.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Pojo dataPojo = new Pojo();
dataPojo.id = json_data.getString("category_id");
dataPojo.fname = json_data.getString("category_name");
dataPojo.thumbnailUrl = json_data.getString("category_image");
dataList.add(i, dataPojo);
JSONArray jArray1 = json_data.getJSONArray("subcategory");
for (int j = 0; j < jArray1.length(); j++) {
JSONObject json_data1 = jArray1.getJSONObject(j);
Pojo dataPojo1 = new Pojo();
dataPojo1.id2 = json_data1.getString("category_id");
dataPojo1.fname2 = json_data1.getString("category_name");
dataList.add(j, dataPojo1);
}
}
dataAdapter = new DataAdapter(dataList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();
}
Above code is a getting a data of Main category but can't getting subcategory data
Below is my Pojo.java class :
public class Pojo {
public String id;
public String fname;
public String thumbnailUrl;
public String id2;
public String fname2;
public Pojo() {
}
public Pojo(String id, String fname, String thumbnailUrl, String id2, String fname2) {
this.id = id;
this.fname = fname;
this.thumbnailUrl = thumbnailUrl;
this.id2 = id2;
this.fname2 = fname2;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public String getId2() {
return id2;
}
public void setId2(String id2) {
this.id2 = id2;
}
public String getFname2() {
return fname2;
}
public void setFname2(String fname2) {
this.fname2 = fname2;
}
}
Json Response:
so how to i solve this can anyone help
EIDT QUESTION AFTER FOLLOWING #Birju ANSWER
Thanks in advance. :)
changes for your Pojo class
public class Pojo {
private String catagory_id;
private String catagory_name;
private String catagory_thumbnailUrl;
private ArrayList<SubCatagory> subCatagoryArrayList;
public ArrayList<SubCatagory> getSubCatagoryArrayList() {
return subCatagoryArrayList;
}
public void setSubCatagoryArrayList(ArrayList<SubCatagory> subCatagoryArrayList) {
this.subCatagoryArrayList = subCatagoryArrayList;
}
public String getCatagory_id() {
return catagory_id;
}
public void setCatagory_id(String catagory_id) {
this.catagory_id = catagory_id;
}
public String getCatagory_name() {
return catagory_name;
}
public void setCatagory_name(String catagory_name) {
this.catagory_name = catagory_name;
}
public String getCatagory_thumbnailUrl() {
return catagory_thumbnailUrl;
}
public void setCatagory_thumbnailUrl(String catagory_thumbnailUrl) {
this.catagory_thumbnailUrl = catagory_thumbnailUrl;
}
}
add new class as SubCatagory
public class SubCatagory {
private String subcatagory_id;
private String subcatagory_name;
public String getSubcatagory_id() {
return subcatagory_id;
}
public void setSubcatagory_id(String subcatagory_id) {
this.subcatagory_id = subcatagory_id;
}
public String getSubcatagory_name() {
return subcatagory_name;
}
public void setSubcatagory_name(String subcatagory_name) {
this.subcatagory_name = subcatagory_name;
}
}
and in your onResponce()
try {
JSONArray jArray = response.getJSONArray("data");
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Pojo dataPojo = new Pojo(); //this is catagory class
dataPojo.setCatagory_id(json_data.getString("category_id"));
dataPojo.setCatagory_name(json_data.getString("category_name"));
dataPojo.setCatagory_thumbnailUrl(json_data.getString("category_image"));
JSONArray jArray1 = json_data.getJSONArray("subcategory");
ArrayList<SubCatagory> subCatagoryArrayList = new ArrayList<>();
for (int j = 0; j < jArray1.length(); j++) {
JSONObject json_data1 = jArray1.getJSONObject(j);
SubCatagory subCatagory = new SubCatagory(); // this is subcatagory class
subCatagory.setSubcatagory_id(json_data1.getString("category_id"));
subCatagory.setSubcatagory_name(json_data1.getString("category_name"));
subCatagoryArrayList.add(subCatagory);
}
dataPojo.setSubCatagoryArrayList(subCatagoryArrayList);//this i insert subcatagory in catagory
dataList.add(dataPojo); // and after i add catagory to datalist
}
/* dataAdapter = new DataAdapter(dataList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(dataAdapter);
dataAdapter.notifyDataSetChanged();*/
}
NOTE: - 1 comment recyclerview and dataadapter and check responce vales in debug mode because i use getter setter for variable (for follow coding structure :dont make variable public...
2 don't replace my code directly...first comment your old code
and inside your
dataadapter -> in method onbindviewholder(){
Pojo catagory=dataList.get(position); // this give you catagory
Arraylist subcatagory =
catagory.getSubCatagoryArrayList();///this is subcatagory
arraylist...using for loop you can get subcatagory data
}
Previously I was reading json data in the following format:
JSON
{
"CreationTime":"2018-01-12T12:32:31",
"Id":"08f81fd7-21f1-48ba-a991-08d559b88cc5",
"Operation":"AddedToGroup",
"RecordType":14,
"UserType":0,
"Version":1,
"Workload":"OneDrive",
"ClientIP":"115.186.129.229",
"UserId":"omaji7#emumbaa10.onmicrosoft.com",
"EventSource":"SharePoint",
"ItemType":"Web"
}
I am reading this json data from a kafka topic and doing some stream processing on it and passing it onto another topic. In processing I have created two json objects, send and received.
Using this code:
final StreamsBuilder builder = new StreamsBuilder();
KStream<String, String> source_o365_user_activity = builder.stream("o365_user_activity");
source_o365_user_activity.flatMapValues(new ValueMapper<String, Iterable<String>>() {
#Override
public Iterable<String> apply(String value) {
System.out.println("========> o365_user_activity_by_date Log: " + value);
ArrayList<String> keywords = new ArrayList<String>();
try {
JSONObject send = new JSONObject();
JSONObject received = new JSONObject(value);
send.put("current_date", getCurrentDate().toString()); // UTC TIME
send.put("activity_time", received.get("CreationTime")); // CONSTANTS FINAL STATIC(Topic Names, Cassandra keys)
send.put("user_id", received.get("UserId"));
send.put("operation_type", received.get("Operation"));
send.put("app_name", received.get("Workload"));
keywords.add(send.toString());
// apply regex to value and for each match add it to keywords
} catch (Exception e) {
// TODO: handle exception
System.err.println("Unable to convert to json");
e.printStackTrace();
}
return keywords;
}
}).to("o365_user_activity_by_date");
This was fairly simple. Now I have a json data with lists in them.
JSON
{
"CreationTime":"2017-12-27T07:47:46",
"Id":"10ee505b-90a4-4ac1-b96f-a6dbca939694",
"Operation":"Add member to role.",
"OrganizationId":"2f88f444-62da-4aae-b8af-8331a6915801",
"RecordType":8,
"ResultStatus":"success",
"UserKey":"10030000A656FE5B#emumbaa10.onmicrosoft.com",
"UserType":0,
"Version":1,
"Workload":"AzureActiveDirectory",
"ObjectId":"mustafa#emumbaa10.onmicrosoft.com",
"UserId":"omaji7#emumbaa10.onmicrosoft.com",
"AzureActiveDirectoryEventType":1,
"ExtendedProperties":[
{
"Name":"Role.ObjectID",
"Value":"b0f54661-2d74-4c50-afa3-1ec803f12efe"
},
{
"Name":"Role.DisplayName",
"Value":"Billing Administrator"
},
{
"Name":"Role.TemplateId",
"Value":"b0f54661-2d74-4c50-afa3-1ec803f12efe"
},
{
"Name":"Role.WellKnownObjectName",
"Value":"BillingAdmins"
}
],
"Actor":[
{
"ID":"omaji7#emumbaa10.onmicrosoft.com",
"Type":5
},
{
"ID":"10030000A656FE5B",
"Type":3
},
{
"ID":"User_d03ca514-adfa-4585-a8bd-7182a9a086c7",
"Type":2
}
],
"ActorContextId":"2f88f444-62da-4aae-b8af-8331a6915801",
"InterSystemsId":"6d402a5b-c5de-4d9f-a805-9371c109e55f",
"IntraSystemId":"a5568d01-f100-497a-b88b-c9731ff31248",
"Target":[
{
"ID":"User_8f77c311-3ea0-4146-9f7d-db21bd052d3d",
"Type":2
},
{
"ID":"mustafa#emumbaa10.onmicrosoft.com",
"Type":5
},
{
"ID":"1003BFFDA67CCA03",
"Type":3
}
],
"TargetContextId":"2f88f444-62da-4aae-b8af-8331a6915801"
}
How can I go about doing the same thing in my Stream processing?
I want to be able to read JSON data against some keys (including the list data keys).
Why not convert JSON to Object and then filter against using the field in Object?
Can't you do like this?
send.put("target_0_id", received.get("Target").getJSONObject(0).get("ID"));
You can use gson library and can convert the json to object and using getter and setter you can build your desired output JSON. You can also parse the input JSON to fetch the JSONArray details. Following is the code how you can do it using POJO.
Input class:
public class Input {
private String UserType;
private String TargetContextId;
private String RecordType;
private String Operation;
private String Workload;
private String UserId;
private String OrganizationId;
private String InterSystemsId;
private ExtendedProperties[] ExtendedProperties;
private String ActorContextId;
private String CreationTime;
private String IntraSystemId;
private Target[] Target;
private Actor[] Actor;
private String Id;
private String Version;
private String ResultStatus;
private String ObjectId;
private String AzureActiveDirectoryEventType;
private String UserKey;
public String getUserType ()
{
return UserType;
}
public void setUserType (String UserType)
{
this.UserType = UserType;
}
public String getTargetContextId ()
{
return TargetContextId;
}
public void setTargetContextId (String TargetContextId)
{
this.TargetContextId = TargetContextId;
}
public String getRecordType ()
{
return RecordType;
}
public void setRecordType (String RecordType)
{
this.RecordType = RecordType;
}
public String getOperation ()
{
return Operation;
}
public void setOperation (String Operation)
{
this.Operation = Operation;
}
public String getWorkload ()
{
return Workload;
}
public void setWorkload (String Workload)
{
this.Workload = Workload;
}
public String getUserId ()
{
return UserId;
}
public void setUserId (String UserId)
{
this.UserId = UserId;
}
public String getOrganizationId ()
{
return OrganizationId;
}
public void setOrganizationId (String OrganizationId)
{
this.OrganizationId = OrganizationId;
}
public String getInterSystemsId ()
{
return InterSystemsId;
}
public void setInterSystemsId (String InterSystemsId)
{
this.InterSystemsId = InterSystemsId;
}
public ExtendedProperties[] getExtendedProperties ()
{
return ExtendedProperties;
}
public void setExtendedProperties (ExtendedProperties[] ExtendedProperties)
{
this.ExtendedProperties = ExtendedProperties;
}
public String getActorContextId ()
{
return ActorContextId;
}
public void setActorContextId (String ActorContextId)
{
this.ActorContextId = ActorContextId;
}
public String getCreationTime ()
{
return CreationTime;
}
public void setCreationTime (String CreationTime)
{
this.CreationTime = CreationTime;
}
public String getIntraSystemId ()
{
return IntraSystemId;
}
public void setIntraSystemId (String IntraSystemId)
{
this.IntraSystemId = IntraSystemId;
}
public Target[] getTarget ()
{
return Target;
}
public void setTarget (Target[] Target)
{
this.Target = Target;
}
public Actor[] getActor ()
{
return Actor;
}
public void setActor (Actor[] Actor)
{
this.Actor = Actor;
}
public String getId ()
{
return Id;
}
public void setId (String Id)
{
this.Id = Id;
}
public String getVersion ()
{
return Version;
}
public void setVersion (String Version)
{
this.Version = Version;
}
public String getResultStatus ()
{
return ResultStatus;
}
public void setResultStatus (String ResultStatus)
{
this.ResultStatus = ResultStatus;
}
public String getObjectId ()
{
return ObjectId;
}
public void setObjectId (String ObjectId)
{
this.ObjectId = ObjectId;
}
public String getAzureActiveDirectoryEventType ()
{
return AzureActiveDirectoryEventType;
}
public void setAzureActiveDirectoryEventType (String AzureActiveDirectoryEventType)
{
this.AzureActiveDirectoryEventType = AzureActiveDirectoryEventType;
}
public String getUserKey ()
{
return UserKey;
}
public void setUserKey (String UserKey)
{
this.UserKey = UserKey;
}
#Override
public String toString()
{
return "ClassPojo [UserType = "+UserType+", TargetContextId = "+TargetContextId+", RecordType = "+RecordType+", Operation = "+Operation+", Workload = "+Workload+", UserId = "+UserId+", OrganizationId = "+OrganizationId+", InterSystemsId = "+InterSystemsId+", ExtendedProperties = "+ExtendedProperties+", ActorContextId = "+ActorContextId+", CreationTime = "+CreationTime+", IntraSystemId = "+IntraSystemId+", Target = "+Target+", Actor = "+Actor+", Id = "+Id+", Version = "+Version+", ResultStatus = "+ResultStatus+", ObjectId = "+ObjectId+", AzureActiveDirectoryEventType = "+AzureActiveDirectoryEventType+", UserKey = "+UserKey+"]";
}}
Target class:
public class Target {
private String Type;
private String ID;
public String getType() {
return Type;
}
public void setType(String Type) {
this.Type = Type;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
#Override
public String toString() {
return "ClassPojo [Type = " + Type + ", ID = " + ID + "]";
}}
Actor class :
public class Actor {
private String Type;
private String ID;
public String getType() {
return Type;
}
public void setType(String Type) {
this.Type = Type;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
#Override
public String toString() {
return "ClassPojo [Type = " + Type + ", ID = " + ID + "]";
}}
ExtendedProperties class :
public class ExtendedProperties {
private String Name;
private String Value;
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public String getValue() {
return Value;
}
public void setValue(String Value) {
this.Value = Value;
}
#Override
public String toString() {
return "ClassPojo [Name = " + Name + ", Value = " + Value + "]";
}}
Main class :
public class Stack {
public static void main(String[] args) {
doIt();
}
private static void doIt() {
String received = "{\"CreationTime\":\"2017-12-27T07:47:46\",\"Id\":\"10ee505b-90a4-4ac1-b96f-a6dbca939694\",\"Operation\":\"Add member to role.\",\"OrganizationId\":\"2f88f444-62da-4aae-b8af-8331a6915801\",\"RecordType\":8,\"ResultStatus\":\"success\",\"UserKey\":\"10030000A656FE5B#emumbaa10.onmicrosoft.com\",\"UserType\":0,\"Version\":1,\"Workload\":\"AzureActiveDirectory\",\"ObjectId\":\"mustafa#emumbaa10.onmicrosoft.com\",\"UserId\":\"omaji7#emumbaa10.onmicrosoft.com\",\"AzureActiveDirectoryEventType\":1,\"ExtendedProperties\":[{\"Name\":\"Role.ObjectID\",\"Value\":\"b0f54661-2d74-4c50-afa3-1ec803f12efe\"},{\"Name\":\"Role.DisplayName\",\"Value\":\"Billing Administrator\"},{\"Name\":\"Role.TemplateId\",\"Value\":\"b0f54661-2d74-4c50-afa3-1ec803f12efe\"},{\"Name\":\"Role.WellKnownObjectName\",\"Value\":\"BillingAdmins\"}],\"Actor\":[{\"ID\":\"omaji7#emumbaa10.onmicrosoft.com\",\"Type\":5},{\"ID\":\"10030000A656FE5B\",\"Type\":3},{\"ID\":\"User_d03ca514-adfa-4585-a8bd-7182a9a086c7\",\"Type\":2}],\"ActorContextId\":\"2f88f444-62da-4aae-b8af-8331a6915801\",\"InterSystemsId\":\"6d402a5b-c5de-4d9f-a805-9371c109e55f\",\"IntraSystemId\":\"a5568d01-f100-497a-b88b-c9731ff31248\",\"Target\":[{\"ID\":\"User_8f77c311-3ea0-4146-9f7d-db21bd052d3d\",\"Type\":2},{\"ID\":\"mustafa#emumbaa10.onmicrosoft.com\",\"Type\":5},{\"ID\":\"1003BFFDA67CCA03\",\"Type\":3}],\"TargetContextId\":\"2f88f444-62da-4aae-b8af-8331a6915801\"}";
JSONObject send = new JSONObject();
Gson gson = new Gson();
Input inputObject = gson.fromJson(received, Input.class);
// you can add values here and customize the output JSON
send.put("userId", inputObject.getUserId());
send.put("Workload", inputObject.getWorkload());
// read Actor list
Actor[] arr = inputObject.getActor();
for (int i = 0; i < arr.length; i++) {
// write your logic here how you want to handle the Actor list
// values
System.out.println(arr[i].getID() + " : " + arr[i].getType());
}
// read ExtendedProperties list
ExtendedProperties[] extendedProperties = inputObject.getExtendedProperties();
for (int j = 0; j < extendedProperties.length; j++) {
// write your logic here how you want to handle the
// ExtendedProperties list values
System.out.println(extendedProperties[j].getName() + " : " + extendedProperties[j].getValue());
}
System.out.println("*************");
}}
alternate main class without using POJO. Here org.json library have been used to parse the input JSON.
public class Test {
public static void main(String[] args) {
doIt();
}
private static void doIt() {
String received = "{\"CreationTime\":\"2017-12-27T07:47:46\",\"Id\":\"10ee505b-90a4-4ac1-b96f-a6dbca939694\",\"Operation\":\"Add member to role.\",\"OrganizationId\":\"2f88f444-62da-4aae-b8af-8331a6915801\",\"RecordType\":8,\"ResultStatus\":\"success\",\"UserKey\":\"10030000A656FE5B#emumbaa10.onmicrosoft.com\",\"UserType\":0,\"Version\":1,\"Workload\":\"AzureActiveDirectory\",\"ObjectId\":\"mustafa#emumbaa10.onmicrosoft.com\",\"UserId\":\"omaji7#emumbaa10.onmicrosoft.com\",\"AzureActiveDirectoryEventType\":1,\"ExtendedProperties\":[{\"Name\":\"Role.ObjectID\",\"Value\":\"b0f54661-2d74-4c50-afa3-1ec803f12efe\"},{\"Name\":\"Role.DisplayName\",\"Value\":\"Billing Administrator\"},{\"Name\":\"Role.TemplateId\",\"Value\":\"b0f54661-2d74-4c50-afa3-1ec803f12efe\"},{\"Name\":\"Role.WellKnownObjectName\",\"Value\":\"BillingAdmins\"}],\"Actor\":[{\"ID\":\"omaji7#emumbaa10.onmicrosoft.com\",\"Type\":5},{\"ID\":\"10030000A656FE5B\",\"Type\":3},{\"ID\":\"User_d03ca514-adfa-4585-a8bd-7182a9a086c7\",\"Type\":2}],\"ActorContextId\":\"2f88f444-62da-4aae-b8af-8331a6915801\",\"InterSystemsId\":\"6d402a5b-c5de-4d9f-a805-9371c109e55f\",\"IntraSystemId\":\"a5568d01-f100-497a-b88b-c9731ff31248\",\"Target\":[{\"ID\":\"User_8f77c311-3ea0-4146-9f7d-db21bd052d3d\",\"Type\":2},{\"ID\":\"mustafa#emumbaa10.onmicrosoft.com\",\"Type\":5},{\"ID\":\"1003BFFDA67CCA03\",\"Type\":3}],\"TargetContextId\":\"2f88f444-62da-4aae-b8af-8331a6915801\"}";
JSONObject send = new JSONObject();
JSONObject input = new JSONObject(received);
// you can add values here and customize the output JSON
send.put("userId", input.getString("UserId"));
send.put("Workload", input.getString("Workload"));
// read Actor list
JSONArray actorArray = input.getJSONArray("Actor");
for (int i = 0; i < actorArray.length(); i++) {
// write your logic here how you want to handle the Actor list
// values
System.out.println(
actorArray.getJSONObject(i).getString("ID") + ":" + actorArray.getJSONObject(i).getInt("Type"));
}
// read ExtendedProperties list
JSONArray extendedProperties = input.getJSONArray("ExtendedProperties");
for (int j = 0; j < extendedProperties.length(); j++) {
// write your logic here how you want to handle the
// ExtendedProperties list values
System.out.println(extendedProperties.getJSONObject(j).getString("Name") + " : "
+ extendedProperties.getJSONObject(j).getString("Value"));
}
System.out.println("*************");
}}
I'm trying to map JSON to Java using gson.I was succesful in writing the logic but unsuccesful in getting the output.Below posted are my JSON and Java files.Any help would be highly appreciated.
This is the output i'm getting
value:null
Below posted is the code for .json files
{
"catitem": {
"id": "1.196289",
"src": "http://feeds.reuters.com/~r/reuters/MostRead/~3/PV-SzW7Pve0/story06.htm",
"orig_item_date": "Tuesday 16 June 2015 07:01:02 PM UTC",
"cat_id": "1",
"heding": "Putin says Russia beefing up nuclear arsenal",
"summary": "KUvdfbefb bngfb",
"body": {
"bpart": [
"KUBINKA,dvdvdvdvgbtgfdnhfbnrtdfbcv dbnfg"
]
}
}
}
Below posted is my .java file
public class offc {
public static void main(String[] args) {
JsonReader jr = null;
try {
jr = new JsonReader(new InputStreamReader(new FileInputStream(
"C:\\Users\\rishii\\IdeaProjects\\rishi\\src\\file3.json")));
} catch (Exception ex) {
ex.printStackTrace();
}
Doll s = new Doll();
Gson g = new Gson();
Doll sr1 = g.fromJson(jr, Doll.class);
System.out.println(sr1);
}
}
Below posted is the code for Doll.java
class Doll {
private catitem ct;
public void setCt(catitem ct) {
this.ct = ct;
}
public catitem getCt() {
return ct;
}
#Override
public String toString()
{
return "value:" + ct;
}
class catitem {
private String id;
private String src;
private String orig_item_date;
private String cat_id;
private String heding;
private String summary;
private body ber;
catitem(String id, String src, String orig_item_date, String cat_id, String heding,
String summary) {
this.id = id;
this.src = src;
this.orig_item_date = orig_item_date;
this.cat_id = cat_id;
this.heding = heding;
this.summary = summary;
}
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setSrc(String src) {
this.src = src;
}
public String getSrc() {
return src;
}
public void setOrig_item_date(String Orig_item_date) {
this.orig_item_date = Orig_item_date;
}
public String getOrig_item_date() {
return getOrig_item_date();
}
public void setCat_id(String cat_id) {
this.cat_id = cat_id;
}
public String getCat_id() {
return cat_id;
}
public void setHeding(String heding) {
this.heding = heding;
}
public String getHeding() {
return heding;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getSummary() {
return summary;
}
public void setBer(body ber) {
this.ber = ber;
}
public body getBer() {
return ber;
}
#Override
public String toString() {
return "id:" + id + "cat_id" + cat_id + "summary" + summary + "orig_date"
+ orig_item_date + "heding" + heding;
}
}
class body {
private String bpart;
public void setBpart(String r) {
this.bpart = r;
}
public String getBpart() {
return bpart;
}
#Override
public String toString() {
return "hiii";
}
}
}
The issue is in class Doll, You have a field ct but in json catitem. Rename the field ct to catitem or if you are using Gson use #SerializedName("catitem") on filed ct and it will work.
I'm new to GSON and have been having trouble parsing the JSON below. The parsing works fine until it gets to the list of bills (staring at "0":). At that point I get a null reference in the resulting gson.fromJson object. If those bills were specified in a JSON array I think it would be easy, but they're not and I can't change that. What is the best way to handle this situation?
{
"status":"OK",
"masterlist":{
"session":{
"session_id":1007,
"session_name":"97th Legislature"
},
"0":{
"bill_id":446875,
"number":"HB4001"
},
"1":{
"bill_id":446858,
"number":"HB4002"
},
"2":{
"bill_id":446842,
"number":"HB4003"
},...
This is the code in my main method:
InputStream source = retrieveStream(url);
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
ResponseData response = gson.fromJson(reader, ResponseData.class);
And this is the ResponseData class:
public class ResponseData {
private String status;
private MasterList masterlist;
public static class MasterList{
private Session session;
private Bill bill; //Also tried: Map<String, String> bill;
}
public static class Session{
private String session_id;
private String session_name;
}
public static class Bill{
private String bill_id;
private String number;
}
}
You can map the object as below:
declare an object to map with json string
public class ResponseData {
private String status;
private Map<String, MasterList> masterlist;
public Map<String, MasterList> getMasterlist() {
return masterlist;
}
public void setMasterlist(Map<String, MasterList> masterlist) {
this.masterlist = masterlist;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public static class MasterList {
private String session_id;
private String session_name;
private String bill_id;
private String number;
public String getSession_id() {
return session_id;
}
public void setSession_id(String session_id) {
this.session_id = session_id;
}
public String getSession_name() {
return session_name;
}
public void setSession_name(String session_name) {
this.session_name = session_name;
}
public String getBill_id() {
return bill_id;
}
public void setBill_id(String bill_id) {
this.bill_id = bill_id;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
}
}
And use it as below:
String data = "{\"status\":\"OK\",\"masterlist\":{ \"session\":{ \"session_id\":1007, \"session_name\":\"97th Legislature\" }, \"0\":{ \"bill_id\":446875, \"number\":\"HB4001\" }, \"1\":{ \"bill_id\":446858, \"number\":\"HB4002\" }, \"2\":{ \"bill_id\":446842, \"number\":\"HB4003\" }}}";
Gson gson = new Gson();
ResponseData response = gson.fromJson(data, ResponseData.class);
for (Iterator<Entry<String, MasterList>> it = response.getMasterlist().entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, MasterList> entry = it.next();
System.out.println(entry.getKey());
System.out.println(entry.getValue().getSession_id());
}