Send JSON object in setVlaue() of PropertyInfo class - json

When I pass a string value in setValue() it calls the web service perfectly. Instead, if I pass a JSON object it shows the "cannot serialize" error. I want to send the JSON object in setValue(). Could somebody help me?
SoapObject request1 = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo unameProp = new PropertyInfo();
unameProp.setName("param");
unameProp.setValue(data);
unameProp.setType(String.class);
request1.addProperty(unameProp);
allowAllSSL.allowAllSSL();
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request1);
HttpTransportSE ht = new HttpTransportSE(URL, 20000);
ht.call(SOAP_ACTION, envelope);

In the line 4, i added toString() to solve the issue and the issue has been resolved.
JSON object:
JSONObject param = new JSONObject();
param.put("loginid", email.toString().trim());
param.put("password", password.toString().trim());
line 4 :
unameProp.setValue(param.toString());

Related

How to replace a JSON value stored in a JSON file and use that in a Rest Assured test

I have a set of input data files in JSON and I am trying to replace a value present in a JSON file and use that value to do a post request in restAssured
The JSON file has
{
"items": [
{
"item_ref": 241,
"price": 100
}
]
}
jsonbody below is a String of the above JSON file
This is the code that fails:
JSONObject jObject = new JSONObject(jsonbody);
jObject.remove("item_ref");
jObject.put("item_ref","251");
System.out.println(jObject);
This is what I am getting:
{"item_ref":"251","items":[{"item_ref":241,"price":100}]}
What I want is {"items":[{"item_ref":251,"price":100}]}
I also tried
JSONObject jObject = new JSONObject(jsonbody);
jObject.getJSONObject("items").remove("item_ref");
jObject.getJSONObject("items").put("item_ref","251");
System
But it says JSONObject["items"] is not a JSONObject.
All I need is to replace the 241 with 251. Is there an easier way to do this?
In general if we have a predefined JSON body file and if we want to replace some of the values in the body and use that in our POST calls within RestAssured, is there any easier way to do it?
The problem is - field item_ref and price are not in JSON Object as you think they are.
They are in JSON Array which contains JSON Objects. In order to modify that value, you have to get elements of the array and THEN execute very similar code you wrote.
Check this out:
JSONObject jObject = new JSONObject(jsonbody);
JSONArray array = jObject.getJSONArray("items");
JSONObject itemObject = (JSONObject) array.get(0); //here we get first JSON Object in the JSON Array
itemObject.remove("item_ref");
itemObject.put("item_ref", 251);
The output is:
{"items":[{"item_ref":251,"price":100}]}
Also, you can create a Hashmap:
HashMap<String,String> map = new HashMap<>();
map.put("key", "value");
RestAssured.baseURI = BASE_URL;
RequestSpecification request = RestAssured.given();
request.auth().preemptive().basic("Username", "Password").body(map).put("url");
System.out.println("The value of the field after change is: " + map.get("key"));

Problems try encode entity to json

im try encode an Doctrine entity as JSON string, to send as Ajax response.
So, i check the doc: The Serializer Component
I try with this code:
$em = $this->getDoctrine()->getManager();
// Get the entities repository
$sesiones_registradas = $em->getRepository('AuditBundle:AuditSession')->findAll();
// Instance the object
$serializer = new Serializer(array(new JsonEncoder()),array(new GetSetMethodNormalizer()));
// Convert only an item
foreach($sesiones_registradas as $sesion){
echo $serializer->normalize($sesion,'json');
break;
}
// Stop script
die();
Last code, fails saying:
Could not normalize object of type
AppsManantiales\AuditBundle\Entity\AuditSession, no supporting
normalizer found.
And if change $serializer->normalize($sesion,'json') by $serializer->serialize($sesion, 'json'); The error message is:
Serialization for the format json is not supported
Any ideas ?.
Your problem come from the fact you inverted both normalizers and encoders.
The line:
$serializer = new Serializer(array(new JsonEncoder()),array(new GetSetMethodNormalizer()));
must be:
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array(new JsonEncoder()));
Use the JMS Serializer Bundle
The docs can be found here: http://jmsyst.com/bundles/JMSSerializerBundle

How to convert a stream back to json?

In a .NET 3.5 Compact Framework / Windows CE app, I need to consume some WebAPI methods that return json. RestSharp looks like it would be great for this, except that it's not quite CF-ready (see Is Uri available in some other assembly than System in .NET 3.5, or how can I resolve Uri in this RestSharp code otherwise? for details).
So, I will probably use HttpWebRequest. I can return the value from the WebAPI methods with this code:
string uri = "http://localhost:48614/api/departments";
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
{
StreamReader reader = new StreamReader(webResponse.GetResponseStream());
MessageBox.Show("Content is " + reader.ReadToEnd());
}
else
{
MessageBox.Show(string.Format("Status code == {0}", webResponse.StatusCode));
}
...but in order to use what's returned from reader.ReadToEnd():
...I need to convert it back to json so that I can then query the data with LINQ to JSON using either JSON.NET (http://json.codeplex.com/) or SimpleJson (http://simplejson.codeplex.com/)
Is that realistically possible (converting StreamReader data to JSON)? If so, how?
UPDATE
I'm trying to deserialize the "json" (or string that looks like json) with this code:
string uri = "http://localhost:48614/api/departments";
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "GET";
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if ((webResponse.StatusCode == HttpStatusCode.OK) && (webResponse.ContentLength > 0))
{
StreamReader reader = new StreamReader(webResponse.GetResponseStream());
DataContractJsonSerializer jasonCereal = new DataContractJsonSerializer(typeof(Department));
var dept = (Department)jasonCereal.ReadObject(reader.ReadToEnd());
MessageBox.Show(string.Format("accountId is {0}, deptName is {1}", dept.AccountId, dept.DeptName));
}
...but get two err msgs on the "var dept =" line:
0) The best overloaded method match for 'System.Runtime.Serialization.XmlObjectSerializer.ReadObject(System.IO.Stream)' has some invalid arguments
1) Argument '1': cannot convert from 'string' to 'System.IO.Stream'
So reader.ReadToEnd() returns a string, and DataContractJsonSerializer.ReadObject() expects a stream, apparently. Is there a better approach for this? Or, if I'm on the right track (although currently a section of track has been removed, so to speak), how should I get past this hurdle?
UPDATE 2
I added the System.Web.Extensions reference and then "using System.Web.Script.Serialization;" but this code:
JavaScriptSerializer jss = new JavaScriptSerializer();
var dept = jss.Deserialize<Department>(s);
MessageBox.Show(string.Format("accountId is {0}, deptName is {1}",
dept.AccountId, dept.DeptName));
...but the second line fails with:
"Type 'bla+Department' is not supported for deserialization of an array."
What type should receive the call to jss.Deserialize()? How is it defined?
Well,
the ReadToEnd() method is used to read the stream into a string and output it. If you need a stream out to pass it to a method requiring a stream, you shouldn't use this method.
From what I read on this page , it seems the BaseStream property of your reader would be more appropriate to use then.

Format JSON String in JSP

I have started working on JSON, I am returning a JSON from JSP through AJAX call. Its working well.
only i need to change the format of my returning JSON String.
Following is the String what my JSP is returing.
[{"VV":0,"desc":"XXXXXXX","amount":0,"date":"12/03/2013","watch":""},{"VV":1,"desc":"XXXXXXX","amount":1,"date":"12/03/2013","watch":""}]
and Below is the String what I want my JSP to return.
{"total":"2","rows":[{"VV":0,"desc":"XXXXXXX","amount":0,"date":"12/03/2013","watch":""},{"VV":1,"desc":"XXXXXXX","amount":1,"date":"12/03/2013","watch":""}] }
Can Any one please help.
Following code I am using to send the output back to front end.
JSONArray arrayObj=new JSONArray();
JSONObject json = new JSONObject();
json.put("VV", i);
json.put("desc", "XXXXXXXXX");
json.put("amount", 1);
json.put("date", "12/03/2013");
json.put("watch", "");
PrintWriter out1 = response.getWriter();
out1.println(arrayObj);
What you need to so with the "json" object that you have created is to allocate to a new variable. Something like this:
arrayObj.put(json);
Next you need to create another object:
JSONObject finalObj = new JSONObject();
finalObj.put("total", 2);
finalObj.put("rows",arrayObj);
finalObj.flush();
I think you need to convert it to String and override the toString() method according to your needs and pass it to your JSP page

RestSharp: get JSON string after deserialization?

using RestSharp is there a way to get the raw json string after it has been deserialized into an object? I need that for debugging purposes.
I'd like to see both the deserialized object and the originally received json string of that object. It's part of a much bigger json string, an item in an array and I only need that specific item json code that's got deserialized into the object.
To help you out this should work, this is a direct example of some of my work, so your's might be a bit different.
private void restClient()
{
string url = "http://apiurl.co.uk/json";
var restClient = new RestClient(url);
var request = new RestRequest(Method.GET);
request.AddParameter("apikey", "xxxxxxxxxx");
restClient.ExecuteAsync<Entry>(request, response =>
{
lstboxtop.Items.Add(response.Content);
});
}
The line lstboxtop is a listbox and using the response.content will literally print the whole api onto your app, if you call it first that would be what you are looking for