how to Deserialize string into object in android - android

how to deserialize below string in android. I have tried below
String json= ls.get(j).getCwc();
Example example = new Gson().fromJson(json,Example.class);
Json
[{
"company":"gjjzh",
"AvgSal":"hjsj"
},
{
"company":"hjd",
"AvgSal":"hjd"
},
{
"company":"hm",
"AvgSal":"lk"
},
{
"company":"er",
"AvgSal":"io"
},
{
"company":"uo",
"AvgSal":"tr"
}]

String json= ls.get(j).getCwc();
Type type = new TypeToken<List<Example>>(){}.getType();
List<Example> example = new Gson().fromJson(json,type);
where Example is
public class Example {
#SerializedName("company")
#Expose
private String company;
#SerializedName("AvgSal")
#Expose
private String avgSal;
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getAvgSal() {
return avgSal;
}
public void setAvgSal(String avgSal) {
this.avgSal = avgSal;
}
}

You'll need to create a model class for the object.
Example.java
public class Example{
String company = "";
String AvgSal = "";
}
and then you need to write code as below to convert JSONArray string into List<Model>.
String json= ls.get(j).getCwc();
Type modelListType = new TypeToken<ArrayList<Example>>(){}.getType();
ArrayList<Example> modelList = new Gson().fromJson(json, modelListType);
This will convert JSONArray into ArrayList.

Related

JSON to Gson - Value cannot be converted to JSONObject7

I'm creating Database from JSON. I get this error when I run app:
Problem parsing the news JSON results
org.json.JSONException: Value Trump of type java.lang.String cannot be converted to JSONObject
Here is code:
private static List<News> extractFeatureFromJson(String newsJSON) {
if (TextUtils.isEmpty( newsJSON )) {
return null;
}
List<News> newsall = new ArrayList<>();
try {
JSONObject data = new JSONObject(newsJSON);
JSONArray results = data.getJSONArray("articles");
for (int i = 0; i < results.length(); i++) {
JSONObject obj = results.getJSONObject(i);
String webTitle = obj.getString("title");
String webUrl = obj.getString("url");
String webImage = obj.getString( "urlToImage" );
List<NewsForDB> newsForDB = new ArrayList<>( );
Gson gson = new Gson();
NewsForDB webTitleForDB=gson.fromJson( extractFeatureFromJson( webTitle ).toString(), NewsForDB.class );
newsForDB.add(webTitleForDB);
NewsForDB urlForDB=gson.fromJson( extractFeatureFromJson( webUrl ).toString(), NewsForDB.class );
newsForDB.add(urlForDB);
NewsForDB webImageForDB=gson.fromJson( extractFeatureFromJson( webImage ).toString(), NewsForDB.class );
newsForDB.add( webImageForDB );
News news = new News(webTitle, webUrl, webImage);
newsall.add(news);
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing the news JSON results", e);
}
return newsall;
}
When there are no this lines of code
List<NewsForDB> newsForDB = new ArrayList<>( );
Gson gson = new Gson();
NewsForDB webTitleForDB=gson.fromJson( extractFeatureFromJson( webTitle ).toString(), NewsForDB.class );
newsForDB.add(webTitleForDB);
NewsForDB urlForDB=gson.fromJson( extractFeatureFromJson( webUrl ).toString(), NewsForDB.class );
newsForDB.add(urlForDB);
NewsForDB webImageForDB=gson.fromJson( extractFeatureFromJson( webImage ).toString(), NewsForDB.class );
newsForDB.add( webImageForDB );
Everything works great, but I'm trying to prepare code to use ActiveAndroid ORM.
Any suggestions?
Thanks!
UPDATE:
I am following first answer from here.
News:
public class News {
private String mWebTitle;
private String mUrl;
private String mImage;
public News(String webTitle, String webUrl, String webImage) {
mWebTitle = webTitle;
mUrl = webUrl;
mImage = webImage;
}
public String getWebTitle() {
return mWebTitle;
}
public String getUrl() {
return mUrl;
}
public String getWebImage() {return mImage;}
}
And here is part of code from QueryUtils, which is before that posted in first question
public static List<News> fetchNewsData(String requestUrl) {
URL url = createUrl( requestUrl );
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest( url );
} catch (IOException e) {
Log.e( LOG_TAG, "Problem making the HTTP request.", e );
}
List<News> news = extractFeatureFromJson( jsonResponse );
return news;
}
And here is NewsForDB.java
import com.activeandroid.Model;
import com.activeandroid.annotation.Column;
import com.activeandroid.annotation.Table;
#Table(name = "NewsDB")
public class NewsForDB extends Model {
#Column(name = "title", unique = true, onUniqueConflict = Column.ConflictAction.REPLACE)
public String title;
#Column(name = "url")
public String url;
#Column(name = "urlToImage")
public String urlToImage;
public NewsForDB(){
super();
}
public NewsForDB(String title, String url, String urlToImage){
super();
this.title = title;
this.url = url;
this.urlToImage = urlToImage;
}
}
Thank You!
you can edit code just like this !
private static List<News> extractFeatureFromJson(String newsJSON) {
if (TextUtils.isEmpty( newsJSON )) {
return null;
}
List<News> newsall = new ArrayList<>();
try {
JSONObject data = new JSONObject(newsJSON);
JSONArray results = data.getJSONArray("articles");
for (int i = 0; i < results.length(); i++) {
Gson gson = new Gson();
JSONObject obj = results.getJSONObject(i);
News news = gson.fromJson(obj.toString() , News.class);
newsall.add(news);
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing the news JSON results", e);
}
return newsall;
}
I think problem occurs when you make recursive in function extractFeatureFromJson when you call extractFeatureFromJson( webTitle ), and so on.
Maybe you should share your class News, NewsForDB, testcases which make exception, and can you tell me the purpose you create an object newsForDB without usage?

How to parse the json objects having special characters in android

I am new to android and I have the json in structure given below. How can it be parsed using json parsing or retrofit ?
{
"1,abcd":[{
"v_id":"1"
}]
"2,efgh":[{
"v_id":"2"
}]
}
Try this
try {
JSONObject jsonObject = new JSONObject("yourresponce");
JSONArray jsonarray = jsonObject.getJSONArray("1,abcd");
for(int i=0;i<jsonarray.length();i++){
JSONObject jsonObject1 = jsonarray.getJSONObject(i);
String v_id = jsonObject1.getString("v_id");
Log.d("seelogcat","values "+v_id);
}
JSONArray jsonarray2 = jsonObject.getJSONArray("2,efgh");
for(int i=0;i<jsonarray2.length();i++){
JSONObject jsonObject1 = jsonarray2.getJSONObject(i);
String v_id = jsonObject1.getString("v_id");
Log.d("seelogcat","values "+v_id);
}
}catch (Exception e){
}
Your json is Invalid Format: your Format should be below like this
{
"1,abcd": [{
"v_id": "1"
}], // here you have to add (,)
"2,efgh": [{
"v_id": "2"
}]
}
You can check here your Json is valid or not https://jsonlint.com/
To get key separate:
Iterator<?> keys = response.keys();
while( keys.hasNext() ) {
String key = (String)keys.next();
if ( jObject.get(key) instanceof JSONObject ) {
System.out.println(key); // here you need splint based on (,)
}
}
You have a comma (,) missing there. Check in jsonlint
{
"1,abcd": [{
"v_id": "1"
}],
"2,efgh": [{
"v_id": "2"
}]
}
Retrofit with Gson can do the rest of the work. The POJO for the response will be as follows:
public class Example {
#SerializedName("1,abcd")
#Expose
private List<_1Abcd> Abcd = null;
#SerializedName("2,efgh")
#Expose
private List<_2Efgh> Efgh = null;
public List<_1Abcd> get1Abcd() {
return Abcd;
}
public void set1Abcd(List<_1Abcd> Abcd) {
this.Abcd = Abcd;
}
public List<_2Efgh> get2Efgh() {
return Efgh;
}
public void set2Efgh(List<_2Efgh> Efgh) {
this.Efgh = Efgh;
}
}
And
public class _1Abcd {
#SerializedName("v_id")
#Expose
private String vId;
public String getVId() {
return vId;
}
public void setVId(String vId) {
this.vId = vId;
}
}
And
public class _2Efgh {
#SerializedName("v_id")
#Expose
private String vId;
public String getVId() {
return vId;
}
public void setVId(String vId) {
this.vId = vId;
}
}

how to get json values in an array

I am completely don't know Json. Now i am working in Android project. I know how to use Array. I have Json file inside of my Asset folder in my Android Project.
and i have to fetch only standard value from json data and store it in an empty array. my json data is,
[
{
"name":"aaa",
"surname":"bbb",
"age":"18",
"div":"A",
"standard":"7"
},
{
"name":"ccc",
"surname":"ddd",
"age":"17",
"div":"B",
"standard":"7"
},
{
"name":"eee",
"surname":"fff",
"age":"18",
"div":"A",
"standard":"8"
},
{
"name":"ggg",
"surname":"hhh",
"age":"17",
"div":"A",
"standard":"7"
},
{
"name":"sss",
"surname":"ddd",
"age":"18",
"div":"A",
"standard":"8"
},
{
"name":"www",
"surname":"ggg",
"age":"17",
"div":"A",
"standard":"7"
},
{
"name":"ggg",
"surname":"ccc",
"age":"18",
"div":"B",
"standard":"6"
}
]
i am not able to get the way through which i can do this. because i have to check each standard in json data and add it to the array created for storing standard valuee so that i can compare that standard values with each satndard values if its already present in array the it can check the next index in josn data and accordingly unique values can get stored on may array.
i dont know to achieve this as i am new to android as well as for json.
Use gson for easy parsing of json
TypeToken> token = new TypeToken>() {};
List animals = gson.fromJson(data, token.getType());
you can use http://www.jsonschema2pojo.org/ to create user class
public class User {
#SerializedName("name")
#Expose
private String name;
#SerializedName("surname")
#Expose
private String surname;
#SerializedName("age")
#Expose
private String age;
#SerializedName("div")
#Expose
private String div;
#SerializedName("standard")
#Expose
private String standard;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getDiv() {
return div;
}
public void setDiv(String div) {
this.div = div;
}
public String getStandard() {
return standard;
}
public void setStandard(String standard) {
this.standard = standard;
}
}
You can do this way:
//Global Declared
ArrayList<String> allStanderds = new ArrayList<>();
allStanderds.clear();
try{
JSONArray araay = new JSONArray(Your_Json_Array_String);
for (int i = 0; i <array.length() ; i++) {
JSONObject jsonObject = new array.getJSONObject(i);
String standard = jsonObject.getString("standard");
if(!allStanderds.contains(standard)){
allStanderds.add(standard);
}
}
}catch (Exception e) {
e.printStackTrace();
}
// use allStanderds ArrayList for SetAdapter for Spinner.
Happy Coding > :)
Use GSON for parsing JSON array.GSON will provide very helpful API
See my previously asked question on SO related to JSON parsing. You will get rough idea
How to parse nested array through GSON
installl GsonFormat plugin in android studio
use your json string to generate an user entity(example:UserEntity.class)
now,you can use UserEntity user=new Gson().fromJson(yourString,UserEntity.class);
now,your json string is storaged in Object user now;
Please try to use this one
try{
String assestValue = getStringFromAssets();
JSONArray arr = new JSONArray(assestValue);
int count = arr.length();
for (int i=0; i < count; i++){
JSONObject obj = arr.getJSONObject(i);
String name = obj.getString("name");
String surname = obj.getString("surname");
String age = obj.getString("age");
String div = obj.getString("div");
String standard = obj.getString("standard");
}
}catch (JSONException e){
e.printStackTrace();
}
public String getStringFromAssets(){
String str = "";
try {
StringBuilder buf = new StringBuilder();
InputStream json = getAssets().open("contents.json");//put your json name
BufferedReader in =
new BufferedReader(new InputStreamReader(json, "UTF-8"));
while ((str = in.readLine()) != null) {
buf.append(str);
}
in.close();
return str;
}catch (Exception e){
e.printStackTrace();
}
return str;
}
Enjoy programming :)

facing some difficulty in json parsing

My json response is below
{
"groups":[
{
"storeId":"440f0991-9ac5-41b9-9e84-d3b2a2d27c13",
"name":"oty",
"description":"ga",
"image":null,
"bookCount":2,
"members":[
{
"bookId":"9b765d0f-3d6f-4fc1-a4a7-af807c39a004",
"bookName":"Anantha"
},
{
"bookId":"f8616ab1-eeb3-403b-8182-b42e39f4b948",
"bookName":"lok"
}
]
}
]
}
My code for parsing json
JSONObject jsonObject = new JSONObject(message);
JSONArray jsonArray = jsonObject.getJSONArray("groups");
for (int i = 0; i < jsonArray.length(); i++) {
String storeid = jsonArray.getJSONObject(i).getString("storeId");
String name = jsonArray.getJSONObject(i).getString("name");
String description =jsonArray.getJSONObject(i).getString("description");
String bookCount = jsonArray.getJSONObject(i).getString("bookCount");
JSONArray memberJsonArray = jsonArray.getJSONObject(i).getJSONArray("members");
for (int j = 0; j < memberJsonArray.length(); j++) {
String bookId = memberJsonArray.getJSONObject(j).getString("bookId");
String bookName = memberJsonArray.getJSONObject(j).getString("bookName")
GroupsDto groupDtoData = new GroupsDto();
groupDtoData.setGroupName(name);
groupDtoData.setGroupServerId(storeId);
groupDtoData.setbookname(bookName);
groupDtoData.setbookid(bookId);
groupDto.add(groupDtoData);
db.addGroups(groupDtoData);
}
}
but I got result as if book name is twice then the storeId is also twice.simillarly increse in no of book name,store id also increse.so it reflect on the list view having duplicate store name.
I/System.out: storeId 440f0991-9ac5-41b9-9e84-d3b2a2d27c13
I/System.out: bookName Ananta
I/System.out: storeId groupid440f0991-9ac5-41b9-9e84-d3b2a2d27c13
I/System.out: bookname Lok
But i want with one storeId there are two book name but store id also getting twice
please give some idea how to parse this type of json.I have facing this problem for json parsing But i want with one storeId there are two book name but store id also getting twice
Serialize and De-serialize using Gson.
1. Create a model Class, for your case would look like below.
public class MyResponse {
#SerializedName("groups")
private List<Groups> groupsList;
public List<Groups> getGroupsList() {
return groupsList;
}
public class Groups {
#SerializedName("storeId")
private String storeId;
#SerializedName("name")
private String name;
#SerializedName("description")
private String description;
#SerializedName("bookCount")
private String bookCount;
#SerializedName("members")
private List<Members> members;
public String getStoreId() {
return storeId;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getBookCount() {
return bookCount;
}
public List<Members> getMembers() {
return members;
}
public class Members {
#SerializedName("bookId")
private String bookId;
#SerializedName("bookName")
private String bookName;
public String getBookName() {
return bookName;
}
public String getBookId() {
return bookId;
}
}
}
}
Make sure you add Gson Lib on your gradle file if using android studio
dependencies {
compile 'com.google.code.gson:gson:2.6.2'
}
Use the response String, for your case is the message object and convert it to a response object like below.
Gson gson = new GsonBuilder().create();
MyResponse myResponse = gson.fromJson(message, MyResponse.class);

How to read this json in android? I am confused with jsonobject and json string

I am confused as to what a JSON Object is and what a JSON String is. Which part is a JSON Object, and which is a JSON String?
JSON example 1:
{
"abc":"v1",
"def":"v2"
}
JSON example 2:
{
"res":"false",
"error":{
"code":101
}
}
Given by your first example:
try {
JSONObject obj = new JSONObject(json);
String abc = obj.get("abc");
String def = obj.get("def");
} catch (Throwable t) {
// Log something maybe?
}
Simply create a JSONObject with that string in the constructor.
JSONObject obj = new JSONObject(your_string_goes_here);
Your JSON string is the entire visual representation that you see (encoded as a string):
{
"abc":"v1",
"def":"v2"
}
You can tell where a specific JSON Object starts and ends within your string, by looking for that opening brace { and the closing brace '}'.
In your examples, this is a JSON Object:
{
"abc":"v1",
"def":"v2"
}
So is this:
{
"res":"false",
"error": {
"code":101
}
}
And this:
{
"code":101
}
Use GSON for parsing & below are the model classes for json1 & json2
public class Json1 {
/**
* abc : v1
* def : v2
*/
private String abc;
private String def;
public String getAbc() {
return abc;
}
public void setAbc(String abc) {
this.abc = abc;
}
public String getDef() {
return def;
}
public void setDef(String def) {
this.def = def;
}
}
Json2
public class Json2 {
/**
* res : false
* error : {"code":101}
*/
private String res;
/**
* code : 101
*/
private ErrorBean error;
public String getRes() {
return res;
}
public void setRes(String res) {
this.res = res;
}
public ErrorBean getError() {
return error;
}
public void setError(ErrorBean error) {
this.error = error;
}
public static class ErrorBean {
private int code;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
}
}
I have used GsonFormatter plugin for creating model classes, Use Gson, It is super easy and you dont need to parse anything
JSON comprises JSONObject & JSONArray.
Json-1 is JSONObject while JSON -2 is also JSONObject which contains another JSONObject with a key "error".JSON String is the string representation of JSONObject which you can get by JSONObject jsonObject = new JSONObject(); String jsonString = jsonObject.toString();
Data is represented in name/value pairs.
"abc":"v1"
Curly braces hold objects and each name is followed by ':'(colon), the name/value pairs are separated by , (comma).
{
"abc":"v1",
"def":"v2"
}
Code Example:
JSONObject obj = new JSONObject(jsonStr);
String abc = obj.get("abc");
Square brackets hold arrays and values are separated by ,(comma).
{
"books": [
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt",
},
{
"id":"07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy",
}
]
}
Code Example:
JSONArray arrBooks = new JSONArray("books");
for (int i = 0; i<=arrBooks.length(); i++){
JSONObject objBook = arrBooks.getJSONObject(i);
String id = c.getString("id");
}

Categories

Resources