I'm attempting to use a json file to store user data for a dummy Android Studio project, and while trying to test the LoginActivity which reads in the file, I'm getting an error
Error:Execution failed for task ':app:mergeDebugResources'.
/Users/james/projects/cwm/app/src/debug/res/values/users.json:1:1: Error: Content is not allowed in prolog.
{
"users": [
{
"name": "James",
"email": "j#gmail.com",
"address": "addr1",
"password": "password",
"usertype": "USER"
},
{
"name": "Kayla",
"email": "k#gmail.com",
"address": "addr1",
"password": "password",
"usertype": "MANAGER"
}
]
}
And here is the code in the LoginActivity that I believe is causing the error:
private String loadJSONFromAsset() {
String json = null;
try {
InputStream is = this.getAssets().open("users.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;
}
private void parseJ() {
try {
JSONObject jsonObject = new JSONObject(loadJSONFromAsset());
if(jsonObject != null) {
JSONArray jsonArray = jsonObject.getJSONArray("users");
if(jsonArray != null) {
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject jo = jsonArray.getJSONObject(i);
if(jo != null) {
String name = (String) jo.get("name");
String email = (String) jo.get("email");
String address = (String) jo.get("address");
String password = (String) jo.get("password");
String userType = (String) jo.get("usertype");
User u = new User(name, email, address, password);
u.setUserType(userType);
userList.put(email, u);
a.setMessage(u.toString());
a.show();
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I've searched stackoverflow and Google for a solution but most answers pertain to XML or JSON unmarshalling, which I don't believe is relevant to what I'm doing but I could be wrong. Thanks in advance!
/Users/james/projects/cwm/app/src/debug/res/values/users.json:1:1: Error: Content is not allowed in prolog.
Please move your users.json from res folder to assets folder and try again.
Because, getAssets() method refers to assets folder.
It's possible that a byte order mark prevents deserialization. Check that your editor doesn't add one.
Related
I have the following code to retrieve Json from raw file:
#Override
protected RecyclerView.Adapter getAdapter() {
if (adapter == null) {
String jsonStr = readRawFile();
Gson gson = new Gson();
VideoPage videoPage = gson.fromJson(jsonStr, VideoPage.class);
adapter = new VideoAdapter(videoPage);
}
return adapter;
}
String readRawFile() {
String content = "";
Resources resources = getContext().getResources();
InputStream is = null;
try {
is = resources.openRawResource(R.raw.video_list);
byte buffer[] = new byte[is.available()];
is.read(buffer);
content = new String(buffer);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return content;
}
File video_list.json : enter image description here
"data": [
{
"title": "Video 1",
"imgUrl": "http://example.com/",
"videoUrl": "http://example.com/",
"docUrl": "http://example.com/"
},
{
"title": "Video 2",
"imgUrl": "http://example.com//",
"videoUrl": "http://example.com/",
"docUrl": "http://example.com/"
},
Now I do not want to get Json from this video_list file, I want to get the Json file from an url containing Json. Can someone help me code again?
I am geting JSON data getting from web service. Below is my code.
How can I decode the json data?
{
"response": [
{
"last_name": "Test",
"id": 279711390,
"first_name": "Vishnu",
"sex": 2,
"photo_50": "https://vk.com/images/camera_50.gif"
}
]
}
How can I parse it? Thanks.
You can keep a POJO class. With the data which you are about to get from server. And parse them and save in that object.
Example:
JSONObject json= new JSONObject(responseString); //your response
try {
JSONArray responseArray = jsonObj.getJSONArray("response");
for (int i = 0; i < responseArray.length(); i++) {
// get value with the NODE key
JSONObject obj = responseArray.getJSONObject(i);
String lastName = obj.getString("last_name");
String firstName = obj.getString("first_name");
//same for all other fields in responseArray
MyResponse myResp = new MyResponse();
myResp.setFirstName(firstName);
myResp.setLastName(lastName);
//set all other Strings
//lastly add this object to ArrayList<MyResponse> So you can access all data after saving
}
}
catch (JSONException e) {
e.printStackTrace();
}
POJO Class:
public class MyResponse{
public String firstName="";
public String lastName="";
//all other fields and getter setters
}
Hope this helps.
You can parse JSON using this code:
str="<The Json>"
try {
JSONObject jObject=new JSONObject(str);
JSONArray menuObject = new JSONArray(jObject.getString("response"));
String lastName;
for (int i = 0; i<menuObject.length(); i++) {
lastName=menuObject.getJSONObject(i).getString("last_name").toString();
...
}
catch (JSONException e) {
e.printStackTrace();
}
Use this code :-
String string = "Your Json"
try {
JSONObject jsonObject=new JSONObject(str);
JSONArray menuObject = new JSONArray(jObject.getJsonArray("response"));
//no need of for loop because you have only one object in jsonArray.
JSONObject oject = menuObject.getJSONObject(0);
String lastName = object.getString("last_name");
String firstName = object.getString("first_name");
Log.d("User Name", firstName + " " + lastName);
catch (JSONException e) {
e.printStackTrace();
}
This question already has answers here:
Sending and Parsing JSON Objects in Android [closed]
(11 answers)
Closed 8 years ago.
i want to parse this json.i have difficulty when i try to parse the following json.suggest me proper way of parsing following json.i edit my code ,noe this is the correct code that i want to parse.
{
"tag":{
"tag1":1,
"tag2": "colour",
"tag3":"value",
"tag4":"value",
"tag5":1,
"tag6":1,
"tag7":true,
"tag8": [
{
"t1":"Red",
"t2":"int",
"t3":1,
"t4":true
},
{
"t1":"Green",
"t2":"int",
"t3":2,
"t4":true
},
{
"t1":"Blue",
"t2":"int",
"t3":3,
"t4":true
}
],
"tag9":null,
"tag10":1
},
"tag":{
"tag1":2,
"tag2": "value",
"tag3":"value",
"tag4":"value",
"tag5":1,
"tag6":1,
"tag7":true,
"tag8": [
{
"t1":"value",
"t2":"value",
"t3":true,
"t4":true,
},
{
"t1":"value",
"t2":"value",
"t3":false,
"t4":true,
}
],
"tag9":1,
"tag10":3
},
"tag":{
"tag1":5,
"tag2": "value",
"tag3":"value",
"tag4":"value",
"tag5":1,
"tag6":1,
"tag7":false,
"tag8": null,
"tag9":null,
"tag10":null
}
}
i had used this code
try {
JSONObject json= (JSONObject) new JSONTokener(loadJSONFromAsset()).nextValue();
JSONObject json2 = json.getJSONObject("tag");
for (int i = 0; i < json.length(); i++) {
int tag1 = (Integer) json2.get("tag1");
String tag2 = (String) json2.get("tag2");
String tag3 = (String) json2.get("tag3");
String tag4 = (String) json2.get("tag4");
int tag5 = (Integer) json2.get("tag5");
int tag6 = (Integer) json2.get("tag6");
boolean tag7 = json2.getBoolean("tag7");
if (!json2.isNull("tag8")) {
JSONArray jArray = json2.getJSONArray("tag8");
JSONObject json_data = null;
for (int i1 = 0; i1 < jArray.length(); i1++) {
json_data = jArray.getJSONObject(i1);
String Label = json_data.getString("t1");
String ValueType = json_data.getString("t2");
int Value = json_data.getInt("t3");
boolean isNextEnabled = json_data.getBoolean("t4");
}
}
int previous = 0;
if (!json2.isNull("tag9")) {
previous= (Integer) json2.get("tag9");
}
int next = 0;
if (!json2.isNull("tag10")) {
next = (Integer) json2.get("tag10");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getAssets().open("myjson");
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;
}
}
i get only last record ,how do i get all data .any help will be appreciated thanks...
You can try to parse your string # http://json.parser.online.fr/ it works nice for me.
From static review of the JSON string it seems you have "tag" element 3 times in your input and due to that parser might get confused. Try to remove duplicate entries and then try.
The JSONOject has a constructor that accepts a string of JSON data. You can use the constructor to parse the JSON string. If the string is valid JSON data, the constructor will return a JSONObject. If the string is NOT valid JSON, the constructor will throw an error. It's good practice to wrap the constructor inside of a try/catch block.
String json = "{name:\"value\"}";
JSONObject item = null;
try{
item = new JSONObject(json);
}catch(Exception exc){
Log.d(TAG, exc.toString());
}
if(item != null){
Log.d(TAG, String.format("name:%s", item.getString("name")));
}
I have local Json file in asset folder.
I use this code to open file
try {
is = getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
jsonString = is.toString();
jsonString = new String(buffer,"UTF-8");
myJson = new JSONObject(jsonString);
jsonArrayData = myJson.getJSONArray("diTich");
int leng = jsonArrayData.length();
for(int i = 0 ; i < leng ; i++) {
mTitle = jsonArrayData.getJSONObject(i).getString("title");
mDescription = jsonArrayData.getJSONObject(i).getString("description");
mAddress = jsonArrayData.getJSONObject(i).getString("address");
mStatus = jsonArrayData.getJSONObject(i).getString("status");
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
My's Json file
{
"ABCD": [
{
"title": "abcd",
"description": "abc",
"address": "bnc",
"image": "abcg",
"status": false
}
]
}
I retrieved value in JsonObject. Now I wanna edit value in this
For example, change value of key "status" from false to true.
How can I do this ? I don't know write replace it !
Thanks you guys !
You use the JSONObject.put() methods of the JSONObject class. So, in your example you could do this:
jsonArrayData.getJSONObject(i).put("status", true);
That will clobber the value that is currently there.
I've a kept one text file in res/raw folder in eclipse. I am showing here the content of that file:
{
"Categories": {
"Category": [
{
"cat_id": "3",
"cat_name": "test"
},
{
"cat_id": "4",
"cat_name": "test1"
},
{
"cat_id": "5",
"cat_name": "test2"
},
{
"cat_id": "6",
"cat_name": "test3"
}
]
}
}
I want to parse this JSON array. How can I do this?
Can anybody please help me??
Thanks in advance.
//Get Data From Text Resource File Contains Json Data.
InputStream inputStream = getResources().openRawResource(R.raw.json);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int ctr;
try {
ctr = inputStream.read();
while (ctr != -1) {
byteArrayOutputStream.write(ctr);
ctr = inputStream.read();
}
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.v("Text Data", byteArrayOutputStream.toString());
try {
// Parse the data into jsonobject to get original data in form of json.
JSONObject jObject = new JSONObject(
byteArrayOutputStream.toString());
JSONObject jObjectResult = jObject.getJSONObject("Categories");
JSONArray jArray = jObjectResult.getJSONArray("Category");
String cat_Id = "";
String cat_name = "";
ArrayList<String[]> data = new ArrayList<String[]>();
for (int i = 0; i < jArray.length(); i++) {
cat_Id = jArray.getJSONObject(i).getString("cat_id");
cat_name = jArray.getJSONObject(i).getString("cat_name");
Log.v("Cat ID", cat_Id);
Log.v("Cat Name", cat_name);
data.add(new String[] { cat_Id, cat_name });
}
} catch (Exception e) {
e.printStackTrace();
}
This is your code:
String fileContent;
JSONObject jobj = new JSONObject(fileContent);
JSONObject categories = jobj.getJSONObject("Categories");
JSONArray listCategory = categories.getJSONArray("Category");
for( int i = 0; i < listCategory.length(); i++ ) {
JSONObject entry = listCategory.getJSONObject(i);
//DO STUFF
}
Android framework has a helper JsonReader in android.util package
Works like a charm, presented great example. In first block small error with absent square bracket '}':
public List readJsonStream(InputStream in) throws IOException {
JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
try {
return readMessagesArray(reader);
} finally {
reader.close();
}
}
Also exists great library from google-devs GSON, which gives you possibility to map json structure straight to Java model: take a look here
Read it into a String
Create a JSONArray with the retrieved String
Use get() methods to retrieve its data