Reading data from Android App using bluetooth - java

I have Java code to receive data in Android App via Bluetooth like the attached code
Java Code
so readMessage will equal = {\"Pin\":\"A4\",\"Value\":\"20\"},{\"Pin\":\"A5\",\"Value\":\"925\"},{\"Pin\":\"A0\",\"Value\":\"30\"}
So I want to take only the values after string \"Value\" from received data so
Can anyone suggest how to make do that?
Thanks

you can parse the readMessage with JSON format
example:
String[] pinValueArr = readMessage.split(",")
for (String pinValue : pinValueArr) {
try {
JSONObject pinValueJSON = new JSONObject(pinValue);
String pin = pinValueJSON.optString("pin", ""); // opt means if parse failed, return default value what is ""
int pin = pinValueJSON.optInt("Value", 0); // opt means if parse failed, return default value what is "0"
} catch (JSONParsedException e) {
// catch exception when parse to JSONObject failed
}
}
And if you want to manage them, you can make a List and add them all.
List<JSONObject> pinValueList = new ArrayList<JSONObject>();
for (String pinValue : pinValueArr) {
JSONObject pinValueJSON = new JSONObject(pinValue);
// ..
pinValueList.add(pinValueJSON);
}

You can use Gson to convert Json to Object.
(https://github.com/google/gson)
Create Model Class
data class PinItem(
#SerializedName("Pin")
val pin: String? = null,
#SerializedName("Value")
val value: String? = null
)
Convert your json.
val json = "[{"Pin":"A4","Value":"20"},{"Pin":"A5","Value":"925"},{"Pin":"A0","Value":"30"}]"
val result = Gson().fromJson(this, object : TypeToken<List<PinItem>>() {}.type)
So now you having list PinItem and you can get all info off it.

Related

GSON raises exception if object type is different

I am using following approach to parse feed into Java Objects.
val gsonBuilder = GsonBuilder()
val gson = gsonBuilder.create()
var homeModel: DataModel?=null
try {
homeModel = gson.fromJson(response, DataModel::class.java)
}catch (ex:java.lang.Exception){
}
This works fine if feed comes in the same format, but it type of some object changes it lands into exception block.
For example, feed some time provides "integers" instead of Object in "data"
#SerializedName("data")
#Expose
private List<MoreData> data = null;
I want to know if there is any possibility in GSON to set specific data to "null" if type does not match.
you need to change your data type of "data" with List<Object> for java or List<Any> for kotlin. probably you will get rid of exception.
#SerializedName("data")
#Expose
private List<Object> data = null;
but you will need to cast items to appropriate types while you are using.
For example:
val item:Int = homeModel[i] as Int //as yourDesiredType
However, if you want to set "data" null when data type is different, you can try:
val model = DataModel()
val json = Gson().toJson(model)
homeModel = Gson().fromJson(json, DataModel::class.java)
try {
if(!homeModel.data.isNullOrEmpty()){
homeModel.data.first() as String //as yourDesiredType
}
}
catch (ex:java.lang.Exception){
homeModel.data = null
}

Can't parse Java JSON string

From my server is get a JSON response like this:
String json = getJsonFromServer();
The server returns this reply (with the double quotes in the beginning and end):
"{\"error\":\"Not all required fields have been filled out\"}";
I then want to get the error field. I have tried to use the JSONObject class to get the string, but it does not work.
System.out.println("The error is: " + new JSONObject().getJSONObject(response).getString("error");
I have try
String response = "{\"error\":\"Not all required fields have been filled out\"}";
JSONParser parser = new JSONParser();
try {
JSONObject json = (JSONObject) parser.parse(response);
System.out.println(json.get("error").toString());
} catch (ParseException ex) {
}
It have working, you can try it and don't forget add json lib json-simple
You seem to be using the wrong JSONObject constructor; in your example, you are trying to fetch an object from a newlay created object - it will never exist.
Try this:
String response = "{\"error\":\"Not all required fields have been filled out\"}";
JSONObject json = new JSONObject( response );
String error = json.getString( "error" );
System.out.println( error );
Yields
Not all required fields have been filled out
edit
Now that you have completely changed the question...
Why not just first strip the first and last char?
So if
String response = "\"{\"error\":\"Not all required fields have been filled out\"}\"";
response = response.substring(1, response.length() - 1));
// Now convert to JSONObject
Your response object has exactly this string?
{"error":"Not all required fields have been filled out"}
The code below printed the expected output:
Object responseObject = "{\"error\":\"Not all required fields have been filled out\"}";
JSONObject jsonObject = new JSONObject(responseObject.toString());
String errorContent = jsonObject.getString("error");
System.out.println(errorContent);

Parsing JSON Data (Android)

Alright. I have a JSON Object sent to me from a server which contains the following data:
{
"result":
[
{"status":"green","type":"data1"},
{"status":"green","type":"data2"},
{"status":"green","type":"data3"}
],
"status":"ok"
}
The data I want to get is the status for the three status values. Data1, data2, and data3 always show up in that order, so I'm now trying to grab the data by index (e.g. data1 = index 0, data2 = index 1, data3 = index 2). How do I do that?
Try following:
String stat1;
String stat2;
String stat3;
JSONObject ret; //contains the original response
//Parse to get the value
try {
stat1 = ret.getJSONArray("results").getJSONObject(0).getString("status");
stat2 = ret.getJSONArray("results").getJSONObject(1).getString("status");
stat3 = ret.getJSONArray("results").getJSONObject(2).getString("status");
} catch (JSONException e1) {
e1.printStackTrace();
}
You would use JSONObject and JSONArray, the entire string is one JSONObject so you would construct one with it.
JSONObject object = new JSONObject(YOUR_STRING_OF_JSON);
Then you can access it with different get methods depending upon your expected type.
JSONArray results = object.getJSONArray("result"); // This is the node name.
String status = object.getString("status");
for (int i = 0; i < results.length(); i++) {
String resultStatus = results.getJSONObject(i).getString("status");
String type = results.getJSONObject(i).getString("type");
Log.w("JSON Result #" + i, "Status: " + resultStatus + " Type: " + type);
}
You need to surround it with a try/catch because JSON access can throw a JSONException.
Try re-factoring via a forEach loop
var testData =
{
"result":
[
{"status":"green","type":"data1"},
{"status":"green","type":"data2"},
{"status":"green","type":"data3"}
],
"status":"ok"
};
var output = new Object;
var resultSet = new Object;
resultSet = testData.result;
resultSet.forEach(function(data)
{
theStatus = data['status'];
theType = data['type']
output[theType] = theStatus;
});
console.log( output['data1'] );
If you've got your models setup to mirror that data set, then you can let GSON (https://code.google.com/p/google-gson/) do a lot of your work for you.
If you want a bit more control, and want to parse the set yourself you can use JSONObject, JSONArray. There's an example of parsing and assembling a json string here: Android create a JSON array of JSON Objects

Blackberry get JSON from web server URL

I have JSON code like this:
[{ "idShipping":"1328448569",
"shippingDesti":"nusa tenggara barat",
"shippingCosts":"21000"
},
{ "idShipping":"1328448543",
"shippingDesti":"nusa tenggara timur",
"shippingCosts":"76000"
}]
I followed a tutorial from this link: BlackBerry read json string from an URL. I changed
private static final String NAME = "name";
from DataParser.java into
private static final String NAME = "idShipping";
but when i run it on a simulator, it showed a popup screen that said that it failed to parse data from MyScreen.java. It means I can get the JSON string, but I can't parse it.
How do I fix it?
For the JSON you've shown, you would parse the idShipping values something like this:
//String response = "[{\"idShipping\":\"1328448569\",\"shippingDesti\":\"nusa tenggara barat\",\"shippingCosts\":\"21000\"},{\"idShipping\":\"1328448543\",\"shippingDesti\":\"nusa tenggara timur\",\"shippingCosts\":\"76000\"}]";
try {
JSONArray responseArray = new JSONArray(response);
for (int i = 0; i < responseArray.length(); i++) {
JSONObject nextObject = responseArray.getJSONObject(i);
if (nextObject.has("idShipping")) {
String value = nextObject.getString("idShipping");
System.out.println("next id is " + value);
}
}
} catch (JSONException e) {
// TODO: handle parsing error here
}
The key, as Signare said, was parsing a JSONArray, and then getting a string value out of that.

How to read Json Format

am a android application programmer and working on JSON right now, i have a format of json, shown in below. i am getting such format form server to my android program but the problem is am unable to show the result in listview.
could provide me the logic to read that json format.
{
"1":
{
"sub1":{"marks":"10",
"maxmarks":"60",
"grade":"D"
},
"sub2":{"marks":"",
"maxmarks":"60",
"grade":""
}
},
"2":
{
"sub3":{"marks":"30",
"maxmarks":"60",
"grade":"B"
},
"sub4":{"marks":"",
"maxmarks":"60",
"grade":""
}
}
}
Use the JSONObject in Android: http://developer.android.com/reference/org/json/JSONObject.html
Here is a good tutorial: http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/
For example:
JSONObject json = new JSONObject(<your json string>);
JSONObject objectOne = json.getJSONObject("1");
JSONObject subOne = objectOne.getJSONObject("sub1");
string marksOne = subOne.getString("marks");
string maxMarksOne = subOne.getString("maxmarks");
string gradeOne = subOne.getString("grade");
There is number of libraries that can help you with the task like Jackson or GSON
What info are you trying to show in your ListView? That will help us help you parse it.
For starters you can separate the data from the two objects using...
//Assuming your original object is named responseObj
JSONObject obj1 = responseObj.getJSONObject("1");
JSONObject obj2 = responseObj.getJSONObject("2");
//Now to get each piece of data
JSONObject s1 = obj1.getJSONObject("sub1");
string marks1 = s1.getString("marks");
string maxMarks1 = s1.getString("maxmarks");
string grade1 = s1.getString("grade");
JSONObject s3 = obj2.getJSONObject("sub3");
string marks3 = s3.getString("marks");
string maxMarks3 = s3.getString("maxmarks");
string grade3 = s3.getString("grade");
From here you have all of the data and can add them to a ListView in a TextView

Categories

Resources