Can't read json file - java

Here's my method where im reading json file.
private void LoadTabaksFromJson() {
InputStream raw = mContext.getResources().openRawResource(R.raw.tabaks);
Reader reader = new BufferedReader(new InputStreamReader(raw));
ListOfTabaks listOfTodos = new Gson().fromJson(reader, ListOfTabaks.class);
List<Tabak> todoList = listOfTodos.getTodoArrayList();
for (Tabak item: todoList){
mDataBase.insert(TabakTable.NAME,null,getContentValues(item));
}
}
public class ListOfTabaks {
protected ArrayList<Tabak> tabakArrayList;
public ArrayList<Tabak> getTodoArrayList(){
return tabakArrayList;
}
}
And Exeption
Caused by: java.lang.NullPointerException: Attempt to invoke interface
method 'java.util.Iterator java.util.List.iterator()' on a null object
reference
at
com.hookah.roma.hookahmix.TabakLab.LoadTabaksFromJson(TabakLab.java:61)
at com.hookah.roma.hookahmix.TabakLab.(TabakLab.java:32)
at com.hookah.roma.hookahmix.TabakLab.get(TabakLab.java:37)
at
com.hookah.roma.hookahmix.TabakListFragment.updateUI(TabakListFragment.java:38)
at
com.hookah.roma.hookahmix.TabakListFragment.onCreateView(TabakListFragment.java:32)
at
android.support.v4.app.Fragment.performCreateView(Fragment.java:2184)
at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1298)
at
android.support.v4.app.FragmentManagerImpl.moveFragmentsToInvisible(FragmentManager.java:2323)
at
android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2136)
And json file :
{
"tabaksArrayList":[
{
"name":"Абрикос",
"description":"Со вкусом Абрикоса",
"rating":"4.1",
"favourite":"1",
"family":"Al fakher"
},
{
"name":"Ананас",
"description":"Со вкусом Ананаса",
"rating":"4.1",
"favourite":"1",
"family":"Al fakher"
},
{
"name":"Апельсин",
"description":"Со вкусом Апельсина",
"rating":"4.1",
"favourite":"1",
"family":"Al fakher"
},
{
"name":"Апельсин с мятой",
"description":"Со вкусом Апельсина с мятой",
"rating":"4.1",
"favourite":"1",
"family":"Al fakher"
},

It looks like your json schema issue, i'm guessing listOfTodos return null. You can refer to this to generate your schema.
But sometimes that tools can make us confuse so i tried to create your schema manually like this:
TabakRoot.java
public class TabakRoot {
#SerializedName("tabaksArrayList")
private List<TabakItem> tabakItem = null;
public List<TabakItem> getTabakItem() {
return tabakItem;
}}
TabakItem.java
public class TabakItem {
#SerializedName("family")
#Expose
private String tabakFamily;
public String getTabakFamily() {
return tabakFamily;
}}
finally
TabakRoot listOfTodos = new Gson().fromJson(reader, TabakRoot.class);
List<TabakItem> todoList = listOfTodos.getTabakItem();

Looks like you are not initialising your ArrayList, try changing:
protected ArrayList<Tabak> tabakArrayList;
for:
protected ArrayList<Tabak> tabakArrayList = new ArrayList<>();

Please put your json file in assets folder
use AsyncTask to protect from ANR like situtation
onBackground(){
String json = null;
try {
InputStream stream = activity.getAssets().open("ur_json_file_in_assets_folder.json");
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
json = new String(buffer, "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return null;
}
return json;
}
then parse in
onPostExecute(String str){
JsonObject object = new JsonObject(str);
JsonArray arr = object.getJsonArray("tabaksArrayList");
...}
more details at ParseJsonFileAsync.java

You're not initialising tabakArrayList, add a constructor to your ListOfTabaks as following
public ListOfTabaks{
tabakArrayList = new ArrayList<>();
}
and you should be fine

Related

Java "string" is not a JSONObject error when I try to parse string to JSON [duplicate]

I am now currently using a weather API from http://wiki.swarma.net/index.php?title=%E5%BD%A9%E4%BA%91%E5%A4%A9%E6%B0%94API/v2 and wished to convert the JSONObject into printable Strings. However, when I am working on the following code, two errors occurred:
public class getApi {
private static final String WEATHER_MAP_URL = "https://api.caiyunapp.com/v2/TAkhjf8d1nlSlspN/121.6544,25.1552/realtime.json";
private static final String WEATHER_TEST_API = "TAkhjf8d1nlSlspN";
public static JSONObject getWeatherJson() {
try {
URL url = new URL( WEATHER_MAP_URL );
HttpURLConnection connection =
(HttpURLConnection)url.openConnection();
connection.addRequestProperty( "x-api-key", WEATHER_TEST_API );
BufferedReader reader = new BufferedReader(
new InputStreamReader( connection.getInputStream()) );
StringBuffer json = new StringBuffer( 1024 );
String tmp;
while( (tmp = reader.readLine()) != null )
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject( json.toString() );
if(data.getJSONObject("status").toString() != "ok" ) {
return null;
}
return data;
}
catch(Exception e) {
e.printStackTrace();
return null;
}
}
public static void main( String[] args ) {
JSONObject WeatherJson = getWeatherJson();
try {
JSONArray details = WeatherJson.getJSONObject("result").getJSONObject("hourly").
getJSONArray("skycon");
System.out.println(details.getJSONObject(0).getJSONObject("value").toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The JSONObject structure, which is also shown in the link above, is like this:
{
"status":"ok",
"lang":"zh_CN",
"server_time":1443418212,
"tzshift":28800,
"location":[
25.1552, //latitude
121.6544 //longitude
],
"unit":"metric",
"result":{
"status":"ok",
"hourly":{
"status":"ok",
"skycon":[
{
"value":"Rain",
"datetime":"2015-09-28 13:00"
},
{
...
}]
}
}
}
The error occurred:
org.json.JSONException: JSONObject["status"] is not a JSONObject.
at org.json.JSONObject.getJSONObject(JSONObject.java:557)
at getApi.getWeatherJson(getApi.java:34)
at getApi.main(getApi.java:45)
Exception in thread "main" java.lang.NullPointerException
at getApi.main(getApi.java:47)
I have looked at similar posts on the topic is not a JSONObject Exception but found that none of them can help me. I suspect that something is wrong with requesting the data, so actually, getWeatherJson() returns a null object and results in the NullPointerException and JSONObjectException.
Can anyone help me with the code?
According to the getJSONObject() Javadoc, this method will throw an exception if the returned object isn't a true JSON object, which it isn't because "status" is a string. As such, try using data.getString("status").
The status field in the JSON document you have posted is not an object. In JSON, objects are enclosed in with {} brackets. The result node however, is a nested object which holds the status key/value pair. Try the following:
JSONObject data = new JSONObject(json.toString());
if(data.getJSONObject("result").get("status").toString() != "ok" ) {
return null;
}

Java update object value to json file using Gson

I have the following JSON file :
{
"btnsAssign": [
{
"btnCode": 1,
"btnItemTXT": "Baguette",
"btnItemCode": 1001,
"btnAvatarPath": "path"
},
{
"btnCode": 2,
"btnItemTXT": "Petit Pain",
"btnItemCode": 1002,
"btnAvatarPath": "path"
}
]
}
I have the below class :
BtnMenuAssignModel.java
public class BtnMenuAssignModel {
#SerializedName("btnsAssign")
#Expose
private List<BtnsAssign> btnsAssign = null;
public List<BtnsAssign> getBtnsAssign() {
return btnsAssign;
}
public void setBtnsAssign(List<BtnsAssign> btnsAssign) {
this.btnsAssign = btnsAssign;
}
}
BtnsAssign.java
public class BtnsAssign {
#SerializedName("btnCode")
#Expose
private Integer btnCode;
#SerializedName("btnItemTXT")
#Expose
private String btnItemTXT;
#SerializedName("btnItemCode")
#Expose
private Integer btnItemCode;
#SerializedName("btnAvatarPath")
#Expose
private String btnAvatarPath;
public Integer getBtnCode() {
return btnCode;
}
public void setBtnCode(Integer btnCode) {
this.btnCode = btnCode;
}
public String getBtnItemTXT() {
return btnItemTXT;
}
public void setBtnItemTXT(String btnItemTXT) {
this.btnItemTXT = btnItemTXT;
}
public Integer getBtnItemCode() {
return btnItemCode;
}
public void setBtnItemCode(Integer btnItemCode) {
this.btnItemCode = btnItemCode;
}
public String getBtnAvatarPath() {
return btnAvatarPath;
}
public void setBtnAvatarPath(String btnAvatarPath) {
this.btnAvatarPath = btnAvatarPath;
}
}
I need to update some object E.G: object btnItemTXT index 1 from "Petit Pain" to "Pain Complet", How can I?
First convert JSON file to BtnMenuAssignModel then modify BtnMenuAssignModel and convert BtnMenuAssignModel to JSON file:
Gson gson = new Gson();
// read initial json from jsonfile.json
FileReader reader = new FileReader(new File("D:\\codes\\gitlab\\jsonfile.json"));
BtnMenuAssignModel newModel = gson.fromJson(reader, BtnMenuAssignModel.class);
// modify the json object
newModel.getBtnsAssign().forEach(btnsAssign -> {
if (btnsAssign.getBtnCode() == 2) {
btnsAssign.setBtnItemTXT("Pain Complet");
}
});
// write new json string into jsonfile1.json file
File jsonFile = new File("D:\\codes\\gitlab\\jsonfile1.json");
OutputStream outputStream = new FileOutputStream(jsonFile);
outputStream.write(gson.toJson(newModel).getBytes());
outputStream.flush();
This is the right code working for me :
String file = "c:/Users/QAXX2121/Documents/a.json";
try {
Gson gson = new Gson();
// read initial json from jsonfile.json
FileReader reader = new FileReader(new File(file));
BtnMenuAssignModel newModel = gson.fromJson(reader, BtnMenuAssignModel.class);
// modify the json object
newModel.getBtnsAssign().forEach(btnsAssign -> {
if (btnsAssign.getBtnCode() == 2) {
btnsAssign.setBtnItemTXT("Taher");
}
});
// write new json string into jsonfile1.json file
File jsonFile = new File(file);
OutputStream outputStream = new FileOutputStream(jsonFile);
outputStream.write(gson.toJson(newModel).getBytes());
outputStream.flush();

Unable to parse JSON data using beans in JAVA

Here is my code for the parsing the JSON file and printing too.:
public class JsonpJsonParser implements IparseJson {
public static void main(String[] args) {
IparseJson parser = new JsonpJsonParser();
try (FileInputStream in = new FileInputStream("data.json")) {
List<QueryResultBean1> results = parser.parseJson(in);
for (QueryResultBean1 result : results) {
System.out.println(result.getHeader().getRequest_id());
}
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public List<QueryResultBean1> parseJson(InputStream in) {
JsonReader reader = Json.createReader(in);
JsonObject json = reader.readObject();
reader.close();
// parse the json object, return something
List<QueryResultBean1> results = new ArrayList<QueryResultBean1>();
JsonArray items = json.getJsonArray("header");
for (JsonValue item : items) {
if (item instanceof JsonObject) {
QueryResultBean1 result = createBean((JsonObject)item);
results.add(result);
}
}
return results;
}
public QueryResultBean1 createBean(JsonObject json) {
QueryResultBean1 bean = new QueryResultBean1();
// you could also change tags to a List
JsonArray array = json.getJsonArray("header");
String[] h1 = new String[array.size()];
for (int i = 0; i < h1.length; i++) {
h1[i] = array.getString(i);
}
bean.setTags(h1);
retrun bean}
Ive tried executing this code for the JSON file:
"header":[
{
"request_id":1547706529870,
"file_name":"Sm-1547706529870.xlsm",
"file_type":"CIR",
"status":"NEW",
"is_end":false
}
GOT THE ERROR AS:
`Exception in thread "main" java.lang.NullPointerExceptionat com.example.webjson.com.webjson.p1.JsonpJsonParser.createBean(JsonpJsonParser.java:60)
NEED HELP TO PARSE THE DATA.JSON FILE IN JAVA
In the code below:
JsonArray array = json.getJsonArray("header");
You are trying to retrieve an JsonArray from String?, you should retrieve the element in array using an index like:
JsonArray array = json.getJsonArray(0);

Parsing JSON and writing it to prefs as a list of custom object

I have a custom model class like this -
public class MyModel implements Parcelable {
String title;
String message;
/**
* Creator method for the Parcel to use.
*/
public static final Parcelable.Creator<MyModel> CREATOR = new Parcelable.Creator<MyModel>() {
public MyModel createFromParcel(Parcel source) {
return new MyModel(source);
}
public MyModel[] newArray(int size) {
return new MyModel[size];
}
};
public void setTitle(final String titleValue) {
title = titleValue;
}
public void setMessage(final String messageValue) {
message = messageValue;
}
public String getTitle() {
return title;
}
public String getMessage() {
return message;
}
public MyModel() {
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.title);
dest.writeString(this.message);
}
private MyModel(Parcel in) {
this.title = in.readString();
this.message = in.readString();
}
}
My JSON in assets folder is -
[
{
"title": "1",
"message": "Hi"
},
{
"title": "2",
"message": "Bye"
},
{
"title": "3",
"message": "Ciao"
}
]
I need to read and parse this JSON and write it as a list of MyModel object into the shared prefs. To write into prefs, I am doing like this -
public void setSteps(final ArrayList<MyModel> steps) {
Gson gson = new Gson();
getPrefs(mContext).edit().putString("steps", gson.toJson(steps)).apply();
}
How can I parse this JSON and write it to the prefs as a list of MyModel object?
The JSON is currently stored in my assets folder.
Later I can read from the prefs and get the list
It's quite simple:
Type listType = new TypeToken<ArrayList<YourClass>>(){}.getType();
List<YourClass> yourClassList = new Gson().fromJson(jsonArray, listType);
public ArrayList<MyModel> getSteps(){
String localData = getPrefs(mContext).getString("steps");
return new Gson().fromJson(localData , new TypeToken<ArrayList<MyModel>>(){}.getType());
}
firstly load json data from asset folder to string:
public String loadJSONFromAsset() {
// check here data available in pref or not
// if available then return string object of pref here else fetch //from asset and set into pref
String json = null;
try {
InputStream is = getActivity().getAssets().open("yourfilename.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;
}
this method will return the string json file then pass your string json into this:
Type listType = new TypeToken<ArrayList<ModelClass>>(){}.getType();
List<ModelClass> yourClassList = new Gson().fromJson(yourJsonString, listType);
Write this code read JSON from your asset folder.
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("yourfilename.txt");
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;
}
Write this code to read array data from your preference file.
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
...
String jsonArray = getPrefs(mContext).getString("steps","[]").apply();
Type stepType = new TypeToken<ArrayList<YourModelClass>>(){}.getType();
ArrayList<YourModelClass> yourClassList = new Gson().fromJson(jsonArray, stepType);
Let's assume that you have data.json file in data folder in your assets.
just try below code to parse your json.
private void getJsonData()
{
String json = null;
try {
InputStream is = getAssets().open("data/data.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();
}
Type listType = new TypeToken<List<MyModel>>(){}.getType();
ArrayList<MyModel> steps = new Gson().fromJson(json, listType);
setSteps(steps);
}
public void setSteps(final ArrayList<MyModel> steps) {
Gson gson = new Gson();
Log.e("~~~~~", gson.toJson(steps));
}
Here is my logcat result :
E/~~~~~: [{"message":"Hi","title":"1"},{"message":"Bye","title":"2"},{"message":"Ciao","title":"3"}]

Adding String to a list in Java

Please have a look at the below code snippet.
I had a look at some solutions provided on stackoverflow for adding String to a list.
They did not work out well in the below case.
#RequestMapping(value = "/rest/EmployeeDept/", method = RequestMethod.GET)
// ResponseEntity is meant to represent the entire HTTP response
public ResponseEntity<EmployeeDeptResponse> getDept()
{
EmployeeDeptResponse deptResponse = new EmployeeDeptResponse();
HttpStatus httpStatus;
List<EmployeeDept> employeeDeptList = new ArrayList<EmployeeDept>();
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(
"http://localhost:8082/rest/EmployeeDept/");
getRequest.addHeader("accept", "application/json");
HttpResponse response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(
new InputStreamReader((response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
employeeDeptList.add(output);
}
deptResponse.setItems(employeeDeptList);
httpClient.getConnectionManager().shutdown();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpStatus = HttpStatus.OK;
return new ResponseEntity<EmployeeDeptResponse>(deptResponse,httpStatus);
}
I am getting an error in the while loop as "add in list can not be applied to java.lang.String"
The list of type "EmployeeDept".The EmployeeDept class looks like this:-
package com.springboot.postrgres.model;
import java.io.Serializable;
public class EmployeeDept implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String dept;
public EmployeeDept() {
}
public EmployeeDept(int id, String dept) {
this.id = id;
this.dept = dept;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDept() {
return dept;
}
public void setDept(String name) {
this.dept = dept;
}
}
In the above code I have a list "employeeDeptList" and a string "Output".
I need to add this string to the list.
Can any of you provide suitable suggestions.
Thanks in advance.
employeeDeptList is of type ArrayList<EmployeeDept>.
List<EmployeeDept> employeeDeptList = new ArrayList<EmployeeDept>();
output on the other hand is of type String
String output;
So when you do employeeDeptList.add(output);, you are trying to add a String to your employeeDeptList, when it should be an EmployeeDept.
So you either make output an EmployeeDept or you rethink what you want to do with it.
As a suggestion, I am going to assume that your output should contain the information you need to create an EmployeeDept. You probably want to parse that information and create a EmployeeDept dept = new EmployeeDept(parsedId, parsedDept); and then add it to employeeDeptList as employeeDeptList.add(dept);
employeeDeptList is a list of EmployeeDept object. You are trying to add a String to the list of EmployeeDept. Which is not posssible unless you change the type of output variable to EmployeeDept.
If you response is a valid json (specified header), why won't you try to map it to objects?
ObjectMapper mapper = new ObjectMapper();
//assuming your response entity content is a list of objects (json array, since you specified header 'application/json'
String jsonArray = String theString = IOUtils.toString(response.getEntity().getContent(), encoding);
employeeDeptList = List<Employee> list = mapper.readValue(jsonString, TypeFactory.defaultInstance().constructCollectionType(List.class, employeeDeptList.class));
//assuming your response is a single object
String json = String theString = IOUtils.toString(response.getEntity().getContent(), encoding);
employeeDeptList.add(mapper.readValue(json, Employee.class));
//assuming every line of content is an object (does not really make sense)
BufferedReader br = new BufferedReader(ew InputStreamReader((response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
employeeDeptList.add(mapper.readValue(output, Employee.class));
}
There is a problem in your code.
while ((output = br.readLine()) != null) {
employeeDeptList.add(output);
}
output is a String and you are trying to add that to a List<EmployeeDept>. You can't do that. If you want to add output to a List, you should create a List of Strings. Something like List<String>
As you mentioned, what you are getting is,
{
"1499921014230": {
"id": 1499921014230,
"dept": "mechanics"
},
"1499921019747": {
"id": 1499921019747,
"dept": "civil"
}
}
If you can change that , you can try to change it to a simple array of objects,
[
{
"id": 1499921014230,
"dept": "mechanics"
},
{
"id": 1499921019747,
"dept": "civil"
}
]
Add below dependency if you use maven, or just add the .jar to the lib,
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
Then try something like this,
while ((output = br.readLine()) != null) {
JSONArray jsonArr = new JSONArray(output);
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
String dept = jsonObj.getString("dept");
int id = jsonObj.getInt("id");
System.out.println("id : " + id + " dept : " + dept);
employeeDeptList.add(new EmployeeDept(id, dept));
}
}

Categories

Resources