I want to create json data of format like this:
{
"Credential":{
"ref1":"Test",
"ref2":"test",
"ref3":"test"
},
"ref4":"data"
}
I tried a lot, but i did not find a way to do this. Can anyone please help me.
EDIT:
I am able to put the data like below:
{
"ref1":"Test",
"ref2":"test",
"ref3":"test"
}
Thanks in advance.
You can always use JSONStringer class to do so,
JSONStringer jsonstr = new JSONStringer()
.object().key("Credential")
.object().key("ref1").value("Test")
.key("ref2").value("test")
.key("ref3").value("test")
.endObject()
.key("ref4").value("data")
.endObject();
Log.i("JSONStringer", jsonstr.toString());
why do not you use google gson?
// get Json string
Gson gson = new Gson();
String strJson = gson.toJson(yourObject);
Is not it a better solution?
Related
What is the best way to cast my response from the server ?
By directly assigning the response to the entity
Ex: authorityStatusWithWorkFlowEntity = response.body();
OR
First Catching it as JsonElement OR JsonArray OR JsonObject and then converting it to specified entity?
Ex: lineEstimationEntity = new Gson().fromJson(response.body().getAsJsonObject(), new TypeToken<LineEstimationEntity>() {
}.getType());
In performance wise which is the best practice?
I know there's lots of Questions about this, and lots of answers too, however I haven't been able to find a solution to this problem yet, and wondered if anyone had some ideas.
Please note, I'm new to Android and have unfortunately inherited this project from an Android developer that's no longer with us.
Here's what I'm dealing with.
I have an Android App, that calls a web service, and gets a response Stream.
I've tried to use
String ScanString = new Scanner(inStream).useDelimiter("\\A").next();
which seems to work and results in a string as follows
{"RegResponseResult":"{\u000d\u000a \"REGISTERED\": true,\u000d\u000a \"COMPANY_URL\": \"http:\/\/111.222.3.444\/ABC\/XYZ.svc\/\"\u000d\u000a}"}
My Problem is .....
When I try to use JSONObject JSONObj = new JSONObject(ScanString) To Convert the string to a JSONObject, The Resutling Object Only has one nameValuePair.
ie: key=RegResponseResult and value={ "REGISTERED": true, \r\n"COMPANY_URL": "http://111.222.3.444/ABC/XYZ.svc/"\r\n}
}"
How can a jet a JsonObject, ignoring the 'RegResponseResult' , and using the Containing Tags instead, so that it ends up looking like this.
ie: JSONObj =
Key=REGESTERD value=true
Key=COMPANY_URL value=http://111.222.3.444/ABC/XYZ.svc
Thanks so much in advance.
The "RegResponseResult" is string so you may have to re-parse it again to get the inner json object.
String innerJson = JSONObj.getString("RegResponseResult");
JSONObject inner = new JSONObject(innerJson);
Thanks for the ideas.
I ended up changing my webservice, to output a stream instead of a string.
Turns out WCF Adds a bunch of \ to the string, which invalidates it as a Json String.
But returning it as a stream, doesn't result in anything being added.
Here's the Stream builder code for the webservice... if anyone else needs it.
//When Reading the DB in the Iaaa.csv
public Stream RegResponse(String DeviceData)
{
// *****connect to db and call stored proc goes here****
// .................
// read parameters back from cmd object.
DeviceRegisterResponse Response = new DeviceRegisterResponse();
Response.REGISTERED = Convert.ToBoolean(cmd.Parameters["REGISTERED"].Value);
Response.COMPANY_URL = Convert.ToString(cmd.Parameters["COMPANY_URL"].Value);
return GenerateStreamFromString(JsonConvert.SerializeObject(Response, Formatting.None));
}
//When passsing it back from the service in the Iaaa.cs
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "REG/{id}")]
Stream RegResponse(string id);
Im using JsonObject to parse a response from an API, the problem is that the resulting String have double quotes, how to get string with no quotes?
JsonElement jelement = new JsonParser().parse(response);
JsonObject jobject = jelement.getAsJsonObject();
String authorization = jobject.get("authorization").toString();
Log.d("mensa","parseado jwt :"+authorization);
so my response looks like...
parseado jwt :"eyJ0eXAiOiJKV1QiLCJhbGciO..."
Actual Json response
{
"authorization": "eyJ0eXAiOiJKV1..."
}
what is the right way to parse this string so i dont get it wrapped with double quotes?
I believe you are using GSON library. No need to trim out your result, gson provide methods for that. try this
String authorization = jobject.get("authorization").getAsString();
Refer Gson API Doc : JsonElement
You are getting Object from Json and then converting to String. jobject.get("authorization").toString(); try to get String.
String authorization = jobject.getString("authorization");
Just trim out the quotes: authorization = authorization.substring(1, authorization.length() - 1)
Edit: You should actually use the getString() method as it will return the actual content as a string, however, the above still works as a quick workaround.
I know how to access to json. Now I get a json response like that:
"2014-02-16T20:27:54+00:00"
https://openligadb-json.heroku.com/api/last_change_date_by_league_saison?league_shortcut=bl1&league_saison=2013
this is not a JSONArray and has no Name. How can I access it?
It is not json formatted data. If you need it in json, you can generate it by yourself like this :
JSONObject json = new JSONObject();
json.put("data", "2014-02-16T20:27:54+00:00" );
json.toString(); // { "data" : ""2014-02-16T20:27:54+00:00" } it is json
In other case you can work with this data as typical String. It depends on what you need to achieve.
Good luck!
In my backend I have a class User which has multiple Trips.
Those trips have multiple user.
This is a circular reference.
I use this code in my rest service to serialize the user object:
Gson gson = new Gson();
return gson.toJson(user, TripUser.class);
In my android app I do the following:
Gson gson = new Gson();
TripUser Tuser = gson.fromJson(data, TripUser.class);
return Tuser;
What can I do about the circular reference exception?
Is there another way to make this work?
You should try to use flexjson 2.1
This would solve your problem because you can chose which items he should serialize to Json etc.
Also this library gives no problems with circular references
I am not fully sure , but u can try like this :
Gson gson = new Gson();
Type type = new TypeToken<TripUser>(){}.getType();
TripUser user = (TripUser) gson.fromJson(data, type);