I'm parsing a json file with this code:
JSONObject stationJson = array.optJSONObject(i);
Station s = new Station();
s.setName(stationJson.optString("name"));
s.setTimestamp(stationJson.optString("last_update"));
s.setNumber(stationJson.optInt("number"));
This is the json file :
{
"number": 123,
"contract_name" : "7500 - London",
"name": "nom station",
"address": "adresse indicative",
}
I would like to display just the "London" in the name section not the Number.
I found this Code Snippet but I don't know how to use it :
case spots:
number = pSpotsJSON.optString("id");
name = pSpotsJSON.optString("name");
address = pSpotsJSON.optString("description");
status = pSpotsJSON.optString("status");
displayName = buildDisplayName(name);
break;
default:
throw new IllegalArgumentException("Cannot parse spots from JSON: unknown provider " + provider.getName());
}
}
private String buildDisplayName(String name) {
String regexp = "[\\d\\s]*([a-zA-Z](.*)$)";
Pattern p = Pattern.compile(regexp);
Matcher m = p.matcher(name);
if (m.find()) {
return m.group();
}
return name;
}
Any help would be great!
What about getting a substring after the "-" of your String?
Would give something like this:
String contractName = stationJson.getString("contract_name");
contractName = contractName.substring(contractName.indexOf("-")+2); //+2 for the minus + space caracters
Related
Hello every one am newly in app development ,I have a json data and there is key (order_id) some time order_id value is return ("order_id": "188") but some time return Integer like that ("order_id": 188) .is there any way to find that is return string or Integer in ios(swift) and android both thanks
here is example of json response
"orders": [
{
"order_id": "188",
"invoice_id": "OR180413-188",
"order_status": "1"
}
]
And some time like that
"orders": [
{
"order_id": 188,
"invoice_id": "OR180413-188",
"order_status": "1"
}
]
Android :
Object order_id = jsonarray.getJsonObject(0).getInt("order_id");
Object invoice_id = jsonarray.getJsonObject(0).getString("invoice_id");
Object order_status= jsonarray.getJsonObject(0).getInt("order_status");
if(order_id instanceOf String)
// do what you want
.....
May be this will help you
Swift
You can use like:
let str = "188" // Your response string or Int here
var sInt:Int = Int()
// Check if 's' is a String
if str is String {
print("Yes, it's a String")
sInt = Int(str)!
print(sInt)
}else{
print("Not a string")
}
Another Way is:
You can forcefully convert it to string and then Int for safer side
let str = "\(strResponse)" // Your String here
let strToInt = Int(str)
You could decode it as string even when it's an integer with Swift 4:
struct Order: Decodable {
private enum CodingKeys: String, CodingKey {
case orderId = "order_id"
}
let orderId: String
init(from decoder: Decoder) throws {
let container = try? decoder.container(keyedBy: CodingKeys.self)
if let orderId = try container?.decodeIfPresent(String.self, forKey: .orderId) {
self.orderId = orderId
} else if let orderId = try container?.decodeIfPresent(Int.self, forKey: .orderId) {
self.orderId = String(orderId)
} else {
throw DecodingError.dataCorrupted(DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Couldn't decode orderId"
))
}
}
}
I have got this kind of json data from a gmail header. How can i parse it to get the value of "delivered to" and "received" in android. Thanks in advance.
[
{"name":"Delivered-To","value":"ayuka******l#gmail.com"},
{"name":"Received","value":"by 10.140.22.233 with SMTP id 96csp129737qgn; Tue, 12 Sep 2017 14:11:47 -0700 (PDT)"},
{"name":"X-Google-Smtp-Source","value":"ADKCNb5EL+VcU9VEZ4HxoicjzSkTx8DxijwG+0LOR+My5P4fQoiAwNEY8LYBEN/kCq+ITzM43nDg"},
{"name":"X-Received","value":"by 10.129.183.31 with SMTP id v31mr14525436ywh.24.1505250707382; Tue, 12 Sep 2017 14:11:47 -0700 (PDT)"}
]
You just need to get the JSON objects by index and then get the json field "name" in this case
JSONArray yourData = new JSONArray(jsonFromGmail); // Put your data inside a JSONArray
String name = "";
try {
for (int i = 0; i < yourData.length(); i++) {//Loop through your JSON array
JSONObject jsonobj = null;
jsonobj = yourData.getJSONObject(i); //Get JSONObjects by index
System.out.println("name : " + i + " = " + jsonobj.getString("name"));
name = jsonobj.getString("name");
// Do whatever you want with the string
}
} catch (JSONException e) {
e.printStackTrace();
}
Hope it helps
This works using Gson (see https://github.com/google/gson for installation instructions and documentation):
String json = "[ {\"name\":\"Delivered-To\",\"value\":\"ayuka******l#gmail.com\"}, {\"name\":\"Received\",\"value\":\"by 10.140.22.233 with SMTP id 96csp129737qgn; Tue, 12 Sep 2017 14:11:47 -0700 (PDT)\"}, {\"name\":\"X-Google-Smtp-Source\",\"value\":\"ADKCNb5EL+VcU9VEZ4HxoicjzSkTx8DxijwG+0LOR+My5P4fQoiAwNEY8LYBEN/kCq+ITzM43nDg\"}, {\"name\":\"X-Received\",\"value\":\"by 10.129.183.31 with SMTP id v31mr14525436ywh.24.1505250707382; Tue, 12 Sep 2017 14:11:47 -0700 (PDT)\"}]";
// parse the JSON string as an array
JsonArray array = new Gson().fromJson(json, JsonArray.class);
String deliveredTo = "";
String received = "";
// iterate through the items of the array
for (int i = 0; i < array.size(); i++) {
// parse each item as a JSON object, extract name and value from it
JsonObject element = array.get(i).getAsJsonObject();
String name = element.get("name").getAsString();
String value = element.get("value").getAsString();
// look for the relevant fields in name; if we found them, set the according values
if (name.equals("Delivered-To")) {
deliveredTo = value;
} else if (name.equals("Received")) {
received = value;
}
}
System.out.println("Delivered to: " + deliveredTo);
System.out.println("Received: " + received);
Before you use this for production, you should of course add some checks for the validity of the Json and not take assumptions like I did here (e.g.: name and value exist on every item in the array).
Works fine.
JSONArray emailHeaderObj = null;
String deliveredTo = " ";
String received = " ";
String Subject = " ";
String from = "";
try {
emailHeaderObj = new JSONArray(emailHeaderString);
for (int i = 0; i < emailHeaderObj.length(); i++) {
JSONObject element = emailHeaderObj.getJSONObject(i);
String name = element.getString("name");
String value = element.getString("value");
switch(name){
case "Date":
received = value;
break;
case "Subject":
Subject = value;
break;
case "From":
from = value;
break;
}
}
} catch (JSONException e) {
e.printStackTrace();
}
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=45.537284299999996,-73.576391125&radius=1000&types=amusement_park|restaurant|cafe|restaurant|library&rankby=distance&key=apikey
I'm using retrofit. Here is my code:
Retrofit api interface:
ublic interface PlaceApiRequestInterface {
#GET("/maps/api/place/nearbysearch/json")
//synch request: all wait on the same thread
public Response getJson(#Query("location") String location,
#Query("radius") String radius,
#Query("rankby") String rankby,
#Query("types") String types,
#Query("key") String key);
}
Then how I set my values
LatLng locationLatLong = obtenirLeCentre(membres);
String location = locationLatLong.latitude+","+locationLatLong.longitude;
//radius_
String radius = ""+radius_;
//rankby_ is an attribute whose value is "distance"
//type
Set<String> uniqueElements = new HashSet<String>(listPreferences_);
listPreferences_.clear();
listPreferences_.addAll(uniqueElements);
String type = "";
int taille = listPreferences_.size();
for(int i = 0 ; i < taille; i++){
if(i == taille - 1)
type += Converter.converter_.nameToPlaceType(listPreferences_.get(i));
else
type += Converter.converter_.nameToPlaceType(listPreferences_.get(i))+"|";
}
setupClient();
//2- get the answer from my http call
String reponseHttp = Converter.converter_.fromResponseToString(get().getJson(location,radius,rankBy,type,googleKey));
I get this as an answer:
{
"html_attributions" : [],
"results" : [],
"status" : "INVALID_REQUEST"
}
Blockquote
Can one help me to discover what is wrong here?
Thanks.
I want to send data like packageid[]=1&packageid[]2. The same applies for the amount. The key will be the same, but the value will be different.My Packageid[] would be same and values would be different.and my question is different.
HashMap<String,String> params1 = new HashMap<String,String>();
params1.put("customerId", String.valueOf(helpervalue));
params1.put("vechileId", String.valueOf(vehicalId));
params1.put("timeslotId", String.valueOf(timeSlotId));
params1.put("registrationYear", String.valueOf(registeryear));
params1.put("franchiseId", String.valueOf(helpervalue2));
params1.put("jobDate", String.valueOf(date));
params1.put("vehicleRegistrationNumber", String.valueOf(register));
params1.put("totalAmount", String.valueOf(total)+"&"+getURlFromArray1(strint));`
private String getURlFromArray1(int arr[]) {
String makeupSTR = "";
for(int val : arr)
makeupSTR += arr1Key+"="+val+"&";
if(makeupSTR.contains("&"))
makeupSTR = makeupSTR.substring(0, makeupSTR.lastIndexOf("&"));
return makeupSTR;
}
I am expecting to send the following query string structure:
?access=true&action=place_order&type=Add&franchiseId=1&jobDate=2016-01-30&customerId=1&vehicleRegistrationNumber=1&vehicleMakeId=1®istrationYear=2016&totalAmount=250.36&packageIds[]=1&packageIds[]=2&packageAmounts[]=20&packageAmounts[]=30
which responds with JSON like
{
status: false,
displayMessage: "This Slot has just been booked. Please Select a different Time Slot."
}
You need to decide how to send this "array". You can simply send it as a ;-separated string: key=val1;val2;val3, for example. In server, you split them using ;.
Example:
String values[] = { "1", "2", "3" };
String all = "";
for (String v : values)
all += v + ";";
all = all.substring(0, all.length() - 1);
String param = "key=" + all;
You can better send json/xml.
I have a html string in in which i am trying to get string between the tag using regexp and finally saving the value to array-list . But i am not able to get the string between the tag so my array-list is always empty.
<span><div style=\'float:left; width:350px;\'>Pharmacie DAR D\'BAGH</div>
my code to get the data using regexp is
private void findTextByRegExp()
{
ArrayList<ArrayList<String>>dataList1 = new ArrayList<ArrayList<String>>();
String pattern3 = "<span><div style=\'float:left; width:350px;\'>";
String pattern4 = "</div>";
String text = readFromFile();
Pattern p = Pattern.compile(Pattern.quote(pattern3) + "(.*?)" +
Pattern.quote(pattern4));
Matcher m = p.matcher(text);
while (m.find()) {
ArrayList<String>dataAdd = new ArrayList<String>();
dataAdd.add(m.group(1));
dataList1.add(dataAdd);
Log.d("Group data", "" + m.group(1));
}
Log.d("MY ARRAY LIST OD DATA", "" + dataList1);
}
please help me how to achieve this using regexp?
try
String pattern3 = "<span><div style=\\'float:left; width:350px;\\'>";