Compare Two JSON object - android

I am having JSON object like
{
key1:value1,
key2:value2
key3:value3
}
and i will write this JSON content to file.(Done)
For next interval of time i am getting JSON Object as
{
key1:newValue1,
key2:value2
key3:newValue3
}
I need to find out difference between each values. and need to write new json into file
{
key1:(value1- newValue1),
key2:(value2 - value2)
key3:(value3- newValue3)
}
How can i achieve it.? Please help.

The code below just iterates through the keys of your testObject, subtracts the value of the object from file and puts the result of this subtraction back to the testObject... Than you can save, or do whatever you want to do with the values in testObject
for(Iterator<String> iterator = testObject.keys(); iterator.hasNext();) {
String key = iterator.next();
try {
int testValue = testObject.getInt(key);
int fileValue = fileObject.getInt(key);
int differenceValue = testValue - fileValue;
testObject.put(key, differenceValue);
} catch (JSONException e) {e.printStackTrace();}
}

Related

Android getJSONObject reordered automatic

I use below code :
JSONObject value = ...;
JSONObject stationList = value.getJSONObject("stationList");
Iterator<String> iter = array.keys();
while (iter.hasNext()) {
try {
String key = iter.next();
String val = array.get(key).toString();
Log.i("res", key+"- "+val);
} catch (JSONException e) {
e.printStackTrace();
}
}
My data sort is :
1- name
3- other
2- your
But output is :
1- name
2- your
3- other
I think JSONObject reorder data with integer key.
How I can fix it and read data without reorder?
JSONObjects are similar to map which stores data as a key value pair without maintaining order.

Parse get multiple objects using their objectIds

I have a ArrayList<String> -named listObjectId below- of objectIds. I'm trying to get all the objects that have an objectId contained in the ArrayList.
The solution I have right now, I think, is very bad from a performance point of view:
for (int i = 0; i < listObjectId.size(); i++) {
ItemModel mItemModelRetrieved = null;
ParseQuery<ItemModel > query = ParseQuery.getQuery(ItemModel .class);
try {
mItemModelRetrieved = query.get(listObjectId.get(i));
subscriber.onNext(mItemModelRetrieved ); //-- I'm using RxJava
} catch (ParseException e) {
Log.e(TAG, "Error Local " + e.getMessage());
}
}
You're using the wrong method. You have the object ids, so create a ParseObject with them using ParseObject.createWithoutData and then fetch the object. Try the following:
List<ParseObject> parseObjects = new ArrayList<>();
for (String objectId : listObjectId) {
parseObjects.add(ParseObject.createWithoutData(ItemModel.class, objectId));
}
ParseObject.fetchAll(parseObjects);
// parseObjects will now contain all data retrieved from Parse.
The error you're getting tells you that the data type of the column you query must be of type Array, not the value you pass into the method.

combining jackson objectmapper and stream parsing

I have an android application, where parsing a json block takes around 250ms. It contains an array, and I only really need the first 6-7 values available immediatly. And I really need to speed up getting to those pieces of the data.
I have a data structure that essentially looks like:
class Data {
List<Map> data = objectmapper_readvalue_data;
public HashMap getItem(int i) {
return data.get(i);
}
}
I was really hoping to do something like this with a JsonParser:
class Data {
List data = new List();
JsonParser p;
public HashMap getItem(int i) {
while (data.length < i) {
data.append(p.parseOneBlockOfData());
}
return data.get(i);
}
}
And only the first 5-6 values will be parsed at the first render, the others I can deal with later. However, I'm missing the "parseOneBlockOfData" function. Of course I can use a StringBuilder to buffer every value in the parse until I find the next entire block, then use a objectParser or that, but I'm not sure what the performance will be like.
Are there any non hackish ways of doing this?
incase anyone googles this:
JsonParser parser = objectMapper.getFactory().createJsonParser(inputStream);
// Keep going until we find filters:
String fieldName = null;
JsonToken token = null;
while (!"filters".equals(fieldName)) {
token = parser.nextToken();
while (token != JsonToken.START_ARRAY) {
token = parser.nextToken();
}
fieldName = parser.getCurrentName();
}
// We're at the filters node
while (parser.nextToken() == JsonToken.START_OBJECT) {
Map x = objectMapper.readValue(parser, Map.class);
}

Parse JSON String array for individual strings/ints

I am getting information from a MySql DB via PHP. The information is returned in the following JSON array:
06-15 15:20:17.400: E/JSON(9865): {"tag":"get_game_state","success":1,"error":0,"GameState":{"monster":"Troll","qty":"1","exp":"0"}}
The json is parsed and string is built using StringBuilder. Now that I have the information returned I want to parse it for the individual strings/ints it contains to put them in a local sqlite db.
Here are the two lines in question
userFunctions.getServerGameState(email, monster, qty, exp); //this line gets the JSON array and the above information is returned
db.saveLocalGameSate(monster, qty, exp); //this line should take that information take String monster int exp and int qty and put them in the local db.
How should I convert that returned information into an individual string and ints so that they can be used in the next line of code? Any direction to some resources would be very helpful.
update
I have added the following lines inbetween the two above lines of code, output is a null pointer exception
try {
JSONArray arr = new JSONArray(GameState);
JSONObject jObj = arr.getJSONObject(0);
String virtumon = jObj.getString("monster");
Integer qty = jObj.getInt("qty");
Integer exp = jObj.getInt("exp");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
That's not actually a JSON array; it's a JSON object (cause of the curly braces instead of square brackets.)
One of the constructors to JSONObject() accepts a string containing JSON and will parse it and create a JSON object. I can't post links yet but see the JSONObject docs at d.android.com.
Once you have a JSONObject you can use getString(), getInt(), optString() and optInt() to pull out the data you need.
Assuming 'responseString' is the full response string:
try {
JSONObject responseObj = new JSONObject(responseString);
JSONObject gameStateObj = responseObj.getJSONObject("GameState");
String monsterType = gameStateObj.getString("monster");
int qty = Integer.parseInt(gameStateObj.getString("qty"));
int exp = Integer.parseInt(gameStateObj.getString("exp");
} catch (JSONException ex) {
e.printStackTrace();
}
"qty" and "exp" are strings in your json so you need to getString then convert to int. I think this code is correct; haven't tested it.

android XML parse into Hash map not working

I am getting the most bizzarre behavior with trying to parse an XML, I run through it step by step and all values are assigned and retrieved in order and then the object I create is added to a HashMap for easy look up, the problem is when I am done retrieving it all the HashMap has null values and the ones that aren't null are the value of the very last node that was read, I have walked through it over and over and it all seems correct, but when it's done loading the values in the HasMap look like:
[0] null
[1] NarrationItem#44e9d170
[2] null
[3] null
[4] NarrationItem#44e9d170
etc, etc.
The format of my XML files is:
<narrations>
<narration id="0" name="A" alias="a" >
<line text="This is a test."></line>
</narration>
<narration id="1" name="B" alias="b" >
<line text="This another a test."></line>
</narration>
<narration id="2" name="C" alias="c" >
<line text="This is STILL a test."></line>
</narration>
</narrations>
And my XML parsing method is follows:
public HashMap<String, NarrationItem> NarrationMap = new HashMap<String, NarrationItem>();
private void LoadNarrationsXML() {
NarrationItem i = new NarrationItem();
String line;
String s;
try {
// Get the Android-specific compiled XML parser.
XmlResourceParser xmlParser = this.getResources().getXml(R.xml.narrations);
while (xmlParser.getEventType() != XmlResourceParser.END_DOCUMENT) {
if (xmlParser.getEventType() == XmlResourceParser.START_TAG) {
s = xmlParser.getName();
if (s.equals("narration")) {
i.Clear();
i.ID = xmlParser.getAttributeIntValue(null, "id", 0);
i.Name = xmlParser.getAttributeValue(null, "name");
i.Alias = xmlParser.getAttributeValue(null, "alias");
} else if (s.equals("line")) {
line = xmlParser.getAttributeValue(null, "text");
i.Narration.add(line);
}
} else if (xmlParser.getEventType() == XmlResourceParser.END_TAG) {
s = xmlParser.getName();
if (s.equals("narration")) {
NarrationMap.put(i.Alias, i);
}
}
xmlParser.next();
}
xmlParser.close();
} catch (XmlPullParserException xppe) {
Log.e(TAG, "Failure of .getEventType or .next, probably bad file format");
xppe.toString();
} catch (IOException ioe) {
Log.e(TAG, "Unable to read resource file");
ioe.printStackTrace();
}
}
The NarrationItem object is a custom object defined as:
public class NarrationItem {
int ID;
String Name;
String Alias;
ArrayList<String> Narration = new ArrayList<String>();
public NarrationItem() { }
public void LoadNarration(int id, String name, String alias, ArrayList<String> narration) {
ID = id;
Name = name;
Alias = alias;
Narration.addAll(narration);// = narration;
}
public void Clear() {
ID = 0;
Name = "";
Alias = "";
Narration.clear();
}
}//End Narration
If someone could point out the problem I'd be very thankful I have sat here staring at this issue for hours.
You're only ever creating one NarrationItem object - you're then using a reference to that object as the value for multiple entries in the map. Don't do that. You need to understand that the map doesn't contain an object as the value - it contains a reference to an object.
You can probably fix this just by creating a new NarrationItem each time instead of calling Clear.
It's not clear how you're looking at the map to see those null values, but if you're using the debugger and looking at the internal data structure, you probably shouldn't really be doing that either - instead, step through the keys, values or entries, i.e. stick within the abstraction that HashMap is meant to support.

Categories

Resources