hi i want to parse my downloaded json file that stored in the SDCard directory ,
i don't know how can i do that !
im google a lot but i can only find somethings like : BuffredReader , InputFileStream , ...
please help me !
here is part of my code but it have the problem i attached in the image :
File GroupsJsonFileAdress = new File(Enviroments.getExternalStorageDirectory() + "FOLDER/G.json");
try {
ObjectInputStream groupsInJson = new ObjectInputStream(new FileInputStream(GroupsJsonFileAdress));
JSONObject jsonObject = (JSONObject)groupsInJson.readObject();
String DATABASE_VERSION = jsonObject.getString("DBVersion");
JSONArray groupsArray = jsonObject.getJSONArray("Groups");
for (int i = 0; i < groupsArray.length(); i++) {
JSONObject groupJsonObjectReader = groupsArray.getJSONObject(i);
int id= groupJsonObjectReader.getInt("Id");
String gTitle = groupJsonObjectReader.getString("title");
Group loaderG = new Group();
loaderG.GroupId = id;
loaderG.Title = gTitle;
Log.i("INFO", loaderG.Title);
groupsClasses.add(loaderG);
}
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
and here is the error i got :
http://i.stack.imgur.com/lQ3YN.jpg
Create a model that matches your Json architecture and then parse it using GSON librarie ;)
Easiest way to do it so far for me :)
Related
Adding backup feature on my app and i am using Realm database, i want to backup it to a json file.
i have created the function for reading the database and create a JSONobject.
While doing the JSONobject.tostring i got a outofmemory error since i have more than 200'000 records.
any other way to create the json file.
RealmResults<StoneModelR> allStones = realm.where(StoneModelR.class).sort("id", Sort.ASCENDING).findAll();
for (StoneModelR singleStone : allStones) {
try {
JSONObject jObjectStone = new JSONObject();
jObjectStone.put("stoneid", singleStone.id);
jObjectStone.put("lat", singleStone.lat);
jObjectStone.put("lng", singleStone.lon);
jObjectStone.put("userid", singleStone.userid);
jObjectStone.put("owner", singleStone.owner);
jObjectStone.put("timestamp", singleStone.timestamp);
jObjectStone.put("stonetype", singleStone.stonetype);
jObjectStone.put("remarks", singleStone.description);
jObjectStone.put("imported", singleStone.imported);
jArrayStones.put(jObjectStone);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
JSONObject stoneObj = new JSONObject();
try {
stoneObj.put("stones", jArrayStones);
} catch (JSONException e) {
e.printStackTrace();
}
I just can not solve this problem. I get the data from the server, save them in shared preferences key = data value = "[.. json].
The structure and type of data can be seen in the screenshot.
How to correctly json in the List <User ..>. I use this code, in which it uses jackson2 library, but it does not work. I'm getting an error
JsonMappingException: Can not deserialize instance of com.example.dmitriysamoilov.filipapp.model.UserContactListModel out of START_ARRAY token
public List<UserContactListModel> getUserLocalContactsData() {
List<UserContactListModel> listModels = new ArrayList<>();
String json = "";
sharedPreferences = context.getSharedPreferences(ReservedName.USER_LOCAL_CONTACTS_DATA,
context.MODE_PRIVATE);
if (sharedPreferences.contains("json")) {
json = sharedPreferences.getString("json", "");
}else return listModels;
ObjectMapper mapper = new ObjectMapper();
try {
// Convert JSON string from file to Object
UserContactListModel l = mapper.readValue(json,UserContactListModel.class);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return listModels;
}
I understand that the logic is not true, but I can not figure this out very long
Since your json is array, try as below
listModels = Arrays.asList(mapper.readValue(json, UserContactListModel[].class));
Giving a short example try to find out your result.
String jsonArray = "[{\"brand\":\"ford\"}, {\"brand\":\"Fiat\"}]";
ObjectMapper objectMapper = new ObjectMapper();
List<Car> cars1 = objectMapper.readValue(jsonArray, new TypeReference<List<Car>>(){});
Here for your code-
public List<UserContactListModel> getUserLocalContactsData() {
List<UserContactListModel> listModels = new ArrayList<>();
String json = "";
sharedPreferences = context.getSharedPreferences(ReservedName.USER_LOCAL_CONTACTS_DATA,
context.MODE_PRIVATE);
if (sharedPreferences.contains("json")) {
json = sharedPreferences.getString("json", "");
}else return listModels;
ObjectMapper mapper = new ObjectMapper();
try {
// Convert JSON string from file to Object
listModels = mapper.readValue(json,new TypeReference<List<UserContactListModel>>(){});
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return listModels;
}
I am creating a stand-alone java program. I have the code to create CSV file and it works when I put it as a string variable (eg: below)
this.btnCreateFile = new JButton("Create File");
this.btnCreateFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
lblOutput.setText(textArea.getText());
String jsonString = "{\"infile\": [{\"field1\": 11,\"field2\": 12,\"field3\": 13},{\"field1\": 21,\"field2\": 22,\"field3\": 23},{\"field1\": 31,\"field2\": 32,\"field3\": 33}]}";
JSONObject output;
try {
output = new JSONObject(jsonString);
JSONArray docs = output.getJSONArray("infile");
File file=new File("/tmp2/fromJSON.csv");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
But, when I change the JSON string to get from a textArea, it shows 'A JSONObject text must begin with '{' at 1 [character 2 line 1]' (eg: below)
this.btnCreateFile = new JButton("Create File");
this.btnCreateFile.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
lblOutput.setText(textArea.getText());
JSONObject output;
try {
output = new JSONObject(textArea);
JSONArray docs = output.getJSONArray("infile");
File file=new File("/tmp2/fromJSON.csv");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Does anyone have any idea on how to fix this? Thanks
This is the JSON String:
{"infile": [{"field1": 11,"field2": 12,"field3": 13},
{"field1": 21,"field2": 22,"field3": 23},
{"field1": 31,"field2": 32,"field3": 33}]}
Try changing this line
output = new JSONObject(textArea);
into
output = new JSONObject(textArea.getText());
I also suggest to print the output of:
textArea.getText()
The text { may not getting detected. Keep the escape character for flower braces.
My java code looks something like this:
public class CreateSolr4Doc {
public static void main(String[] args) {
int recordCount = 3;
CreateSolr4Doc instance = new CreateSolr4Doc();
instance.createDummyData(recordCount);
}
private void createDummyData(int recordCount) {
String url = "http://localhost:8983/solr/collection1";
System.out.println(url);
HttpSolrServer solr = new HttpSolrServer(url);
for (int index = 0; index < recordCount; index++) {
for(int j=1;j<=20000;j++)
{
SolrInputDocument doc = new SolrInputDocument();
Date date = new Date();
doc.addField("id","ibsfdjkhfb"+index+j);
doc.addField("mongoid", "4eebb9db43d7391c16509153");
doc.addField("agency","AFP");
doc.addField("title","Masked men loot cash, cellphones"+(index+1));
doc.addField("story",(index+1) + "PATNA: Giving a damn to");
doc.addField("mimetype","TEXT");
doc.addField("subject","The criminals first reached the office-cum")
doc.addField("coverage","patna");
doc.addField("isSyndicated",1);
doc.addField("createdDate",org.apache.commons.lang.time.DateUtils.addDays(date, -(index+101)));
doc.addField("expiryDate","2061-12-17T03:06:13Z");
doc.addField("language","en");
doc.addField("version","1.0");
doc.addField("ingestionDate","2011-12-16T21:36:28.296Z");
doc.addField("ingestionDate_index","2011-12-17T03:06:00Z");
System.out.println("Inserting document"+" "+(j)+" "+(index+1));
try {
solr.add(doc);
} catch (SolrServerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
UpdateResponse response = solr.commit();
System.out.println(response);
} catch (SolrServerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
When I insert data I get an error message something like this:-
Inserting document 1 1
Exception in thread "main" org.apache.solr.common.SolrException: ERROR: [doc=ibsfdjkhfb01] unknown field 'mongoid'
The error is encountered when i add fields in the document.
I don't know how to proceed.
Based on the error message, it appears that you have a field that is not in your schema. Try adding mongoid to your schema.xml and see if that helps.
I'm working on a school project which consist in creating race-tournaments
I'm having an issue right now because I have multiple races-type (CarRace/BikeRace) which have Race as a parent
I'm saving an array of races no matter the specific type.
And now I need to load this list of races
public static ArrayList<Course> loadLRace(String name) {
File inFile = new File(name+".txt");
FileInputStream inFileStream;
ArrayList<Race> lRace = new ArrayList<Race>();
try {
inFileStream = new FileInputStream(inFile);
ObjectInputStream inObjectStream = new ObjectInputStream(inFileStream);
int length = inObjectStream.readInt();
for(int i = 0; i < length; i++) {
Race race = (Race)inObjectStream.readObject();
lRace.add(Race);
}
inObjectStream.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
return lRace;
}
And I'm having a "non valid constructor" error, I guess this is because I don't deal with CarRace AND BikeRace separately, but how can I ?