I can't find any solution for my issue. Many I've tried doesn't work. Could someone help me?
I have a JSON like this:
{
"device": {
"sdk_revision": "dev",
"sdk_type": "android",
"app_id": "0518101906",
"app_version": "0.0.0"
},
"request": {}
}
in my request step in soapUI (RestProject).
I'd like to change the app_id value in this JSON, so in my groovy script I do:
import groovy.json.JsonSlurper
def today = new Date()
appId = today.format("MMddHHmmss")
def extractSelectionJson(String from) {
def slurper = new JsonSlurper()
def holderData = slurper.parseText(context.expand('${'+ from +'#Request}'))
appIdKey = holderData["device"]["app_id"]
appIdKey = appId
}
extractSelectionJson("SessionCreate")`
appId changed only locally, at my json request I have still "app_id": "0518101906" although I've tried setPropertyValue(), updateProperty() (maybe not right way).
For something simple like this, you can use just a one-liner:
{
"device": {
"sdk_revision": "dev",
"sdk_type": "android",
"app_id": "${=String.format('%tm%td%tH%tM%tS'
, new Date()
, new Date()
, new Date()
, new Date()
, new Date())}",
"app_version": "0.0.0"
},
"request": {}
}
If you need details for the String.format(), it is in the documentation.
Related
How can I update a certain field in tfs web with Python?
I have connected to tfs and have received an HTML response.
I have a json with the data that I would like to insert to tfs testCases field.
JSON:
data = json.loads(url.read().decode()) (Json external data)
HTML:
tfsResponse = requests.get(tfsApi, auth=HttpNtlmAuth(username, password))
if tfsResponse.ok:
print(tfsResponse)
soup = BeautifulSoup(tfsResponse.text, 'lxml')
How can I do it?
It's not able to directly use Jenkins automation tests results to update TFS test case.
You need use Rest API to handle this. You need to extract the test results fist then update them to TFS server.
With using below Rest API:
PATCH https://dev.azure.com/{organization}/{project}/_apis/test/Runs/{runId}/results?api-version=5.1
Sample body
[
{
"state": "Completed",
"testPoint": {
"id": 10
},
"outcome": "Passed",
"testCase": {
"id": 4567
}
}
]
If you want to use code, a code snippet for your reference, should similar to Python:
try
{
var u = new Uri("https://{My Account}.visualstudio.com");
VssCredentials c = new VssCredentials(new Microsoft.VisualStudio.Services.Common.VssBasicCredential(string.Empty, "PAT"));
var connection = new VssConnection(u, c);
var testClient = connection.GetClient<TestManagementHttpClient>();
int testpointid = 1;
string teamProject = "MyProjectName";
RunCreateModel run = new RunCreateModel(name: "TestCase Name", plan: new Microsoft.TeamFoundation.TestManagement.WebApi.ShallowReference("TestPlan Id"), pointIds: new int[] { testpointid });
TestRun testrun = testClient.CreateTestRunAsync(run, teamProject).Result;
TestCaseResult caseResult = new TestCaseResult() { State = "Completed", Outcome = "passed", Id = 100000 };
var testResults = testClient.UpdateTestResultsAsync(new TestCaseResult[] { caseResult }, teamProject, testrun.Id).Result;
RunUpdateModel runmodel = new RunUpdateModel(state: "Completed");
TestRun testRunResult = testClient.UpdateTestRunAsync(runmodel, teamProject, testrun.Id, runmodel).Result;
}
catch (AggregateException e)
{
Console.WriteLine(e.InnerException.Message);
}
Below is the json response
{
"details": [
{
"UserName": "john",
"id": "abc_123",
"LastName": "smith"
}
]
}
I need to delete only the UserName parameter :
request.delete("http://localhost:8080/details/id/UserName");
The above code does not seem to work and my expected is as below
{
"details": [
{
"id": "abc_123",
"LastName": "smith"
}
]
}
Please check for the Minimal, Complete, and Verifiable example before posting a question on SO, There are people to help but we would need to know what you've tried beforehand.
To answer your question, You should use a PUT and not a DELETE cause you are trying to update the payload. DELETE as the name suggests will delete the complete resource
Check this link for more detail
PUT calls are resource specific so you will have to mention which entity should be affected.
I have come up with a sample code based on the details you've provided
Used HashMap here but you could also post the body as such or use POJO or JSONObject
{
Map < String, Object > map = new HashMap < > ();
map.put("details", Arrays.asList(new HashMap < String, Object > () {
{
put("id", "abc_123");
put("LastName", "smith");
}
}));
RequestSpecification req = RestAssured.given();
req.header("Content-Type", "application/json");
req.body(map).when();
Response resp = req.put("http://localhost:8080/details/id/abc_123");
String body = resp.asString();
System.out.println("Response is : " + body);
}
I receive a JSon string from WS. It's so long that I can't use Json2charp to parse it and receive the structurated class.
I want to parse the string with a command. How is it possible?
I don't know the classes so I can't use a command like:
Dim result = JsonConvert.DeserializeObject(Of MyClass.RootObject)(String_From_File)
Is it possible from the string to obtain the class without using json2charp site ?
For example, in vs.net if on the variable 'string_from_file' I choose 'Json Visualizer' and see all classes and data in correct mode.
How can I obtain the same in my code ?
I have installed Newtonsoft.json
If you cannot use the json to class mappers like NewtonSoft.Json. You can use the Windows.Data.Json api. It let you parse and extract the data you want from your JSON string.
JsonValue jsonValue = JsonValue.Parse("{\"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"IDs\": [116, 943, 234, 38793]}");
double width = jsonValue.GetObject().GetNamedNumber("Width");
double height = jsonValue.GetObject().GetNamedNumber("Height");
string title = jsonValue.GetObject().GetNamedString("Title");
JsonArray ids = jsonValue.GetObject().GetNamedArray("IDs");
You can find a sample in the Windows Universal Sample GitHub.
A complex object parsing is shown here. I've extracted the most relevant parts here. The JSON string is provided to the User constructor which is extracting what it needs and then delegating the parsing to the nested School constructor.
{
"id": "1146217767",
"phone": null,
"name": "Satya Nadella",
"education": [
{
"school": {
"id": "204165836287254",
"name": "Contoso High School"
},
"type": "High School"
},
{
"school": {
"id": "116138758396662",
"name": "Contoso University"
},
"type": "College"
}
],
"timezone": -8,
"verified": true
}
This JSON fragment is parsed with this code:
public User(string jsonString) : this()
{
JsonObject jsonObject = JsonObject.Parse(jsonString);
Id = jsonObject.GetNamedString(idKey, "");
IJsonValue phoneJsonValue = jsonObject.GetNamedValue(phoneKey);
if (phoneJsonValue.ValueType == JsonValueType.Null)
{
Phone = null;
}
else
{
Phone = phoneJsonValue.GetString();
}
Name = jsonObject.GetNamedString(nameKey, "");
Timezone = jsonObject.GetNamedNumber(timezoneKey, 0);
Verified = jsonObject.GetNamedBoolean(verifiedKey, false);
foreach (IJsonValue jsonValue in jsonObject.GetNamedArray(educationKey, new JsonArray()))
{
if (jsonValue.ValueType == JsonValueType.Object)
{
Education.Add(new School(jsonValue.GetObject()));
}
}
}
public School(JsonObject jsonObject)
{
JsonObject schoolObject = jsonObject.GetNamedObject(schoolKey, null);
if (schoolObject != null)
{
Id = schoolObject.GetNamedString(idKey, "");
Name = schoolObject.GetNamedString(nameKey, "");
}
Type = jsonObject.GetNamedString(typeKey);
}
If you cannot use the automatic mapping from NewtonSoft.Json, you have no other way than doing it yourself.
Is not so simple.
The Json i received is very complicated and have many class
So i can't use
double width = jsonValue.GetObject().GetNamedNumber("Width");
Inside class i have more ...
I have been experimenting with the groovy Jsonbuilder as you can see below trying to look at different ways to build JSON objects and arrays. After things started to make sense, I tried expanding to what is shown below. The question I have is, why does "content" show up in the json pretty string output? I actually have another json object displaying this.class information in json string outputs.
Any ideas? I'm new to this, so it could definitely be an obvious one.
def tt = ["test", "test1"]
def jjj = "jason"
def js3 = new groovy.json.JsonBuilder()
def js2 = new groovy.json.JsonBuilder(tt);
js3 hello: "$jjj", "$jjj": tt
def js4 = new groovy.json.JsonBuilder()
def result = js4([sdn: js3, openflow: js2, type: 3])
println js4.toPrettyString();
outputs:
{
"sdn": {
"content": {
"hello": "jason",
"jason": [
"test",
"test1"
]
}
},
"openflow": {
"content": [
"test",
"test1"
]
},
"type": 3
}
The problem can be restated as...
why does this:
import groovy.json.*
def js3 = new JsonBuilder(["test", "test1"])
def js4 = new JsonBuilder(js3)
println js4.toString()
print:
{"content":["test","test1"]}
and this:
import groovy.json.*
def js3 = new JsonBuilder(["test", "test1"])
def js4 = new JsonBuilder(js3.content)
println js4.toString()
prints this (?) :
["test","test1"]
The short answer is that JsonBuilder has a member named content, which represents the payload. When one JsonBuilder absorbs another, we want to replace the payload, and not nest it. This line is the way to replace the payload:
def js4 = new JsonBuilder(js3.content)
Ultimately, this stems from the fact that JsonBuilder.toString() (code here) calls JsonOutput.toJson(object) (code here).
An exercise for the reader is to experiment with:
class MyBuilder {
def content
}
def myB = new MyBuilder(content: ["test", "test1"])
println JsonOutput.toJson(myB)
println JsonOutput.toJson(myB.content)
I am querying twitter api to get the tweets with a hashtag in grails 2.1.1.
My Controller is
import grails.converters.*
import org.codehaus.groovy.grails.web.json.*; // package containing JSONObject, JSONArray,...
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
class NepTweetController {
def index() {
//def restEndpointUrl = "http://search.twitter.com/search.json?q=%23nepal";
def restEndpointUrl = "http://search.twitter.com/search.json?q=%23nepal";
def http = new HTTPBuilder(restEndpointUrl);
// perform a GET request, expecting JSON response data
http.request( GET, JSON ) {
//uri.path = '/search.json'
//uri.query = [ q: '%23nepal' ]
response.success = { resp, json ->
// def tweetsResult = json.results;
// List parsedList = JSON.parse(json) as List;
// JSONObject tweetJson = JSON.parse(json);
//def tweetJson = JSON.parse(json);
def tweets = new JSON(json) as Map;
render(view: "index", model: [message: "Request sent" , tweets: tweets]);
}
}//end of request
}//end of method
}
I successfully get the json response as follows :
{
"completed_in": 0.017,
"max_id": 271907240007581696,
"max_id_str": "271907240007581696",
"next_page": "?page=2&max_id=271907240007581696&q=%23nepal%2F",
"page": 1,
"query": "%23nepal%2F",
"refresh_url": "?since_id=271907240007581696&q=%23nepal%2F",
"results": [
{
"created_at": "Fri, 23 Nov 2012 09:25:12 +0000",
"from_user": "iBshnu",
"from_user_id": 25051623,
"from_user_id_str": "25051623",
"from_user_name": "Bishnu Bhattarai",
"geo": null,
"id": 271907240007581696,
"id_str": "271907240007581696",
"iso_language_code": "ne",
"metadata": {
"result_type": "recent"
},
"profile_image_url": "http:\/\/a0.twimg.com\/profile_images\/2622309791\/42z33jnw1kak9ttyqkrf_normal.jpeg",
"profile_image_url_https": "https:\/\/si0.twimg.com\/profile_images\/2622309791\/42z33jnw1kak9ttyqkrf_normal.jpeg",
"source": "<a href="http:\/\/twitter.com\/">web<\/a>",
"text": "RT #dipakbhattarai: \u0930\u093e\u0937\u094d\u091f\u094d\u0930\u092a\u0924\u093f \u0921\u093e. \u0930\u093e\u092e\u092c\u0930\u0923 \u092f\u093e\u0926\u0935\u0926\u094d\u0935\u093e\u0930\u093e \u092e\u0919\u094d\u0938\u093f\u0930 \u0967\u096a \u092d\u093f\u0924\u094d\u0930 \u0926\u0932\u0939\u0930\u0941\u0932\u093e\u0908 \u0930\u093e\u0937\u094d\u091f\u094d\u0930\u093f\u092f \u0938\u0939\u092e\u0924\u093f\u0915\u094b \u0938\u0930\u0915\u093e\u0930 \u092c\u0928\u093e\u0909\u0928 \u0906\u0935\u094d\u0939\u093e\u0928\u0964 #Nepal",
"to_user": null,
"to_user_id": 0,
"to_user_id_str": "0",
"to_user_name": null
},
{
"created_at": "Fri, 23 Nov 2012 09:24:58 +0000",
"from_user": "Phanindra07",
"from_user_id": 63104333,
"from_user_id_str": "63104333",
"from_user_name": "Phanindra Dahal",
"geo": null,
"id": 271907179404095488,
"id_str": "271907179404095488",
"iso_language_code": "en",
"metadata": {
"result_type": "recent"
},
"profile_image_url": "http:\/\/a0.twimg.com\/profile_images\/2417859753\/febstuo4p4zltimnpky0_normal.jpeg",
"profile_image_url_https": "https:\/\/si0.twimg.com\/profile_images\/2417859753\/febstuo4p4zltimnpky0_normal.jpeg",
"source": "<a href="http:\/\/twitter.com\/">web<\/a>",
"text": "RT #DeepakAdk: Chef's assault on #Nepal #Maoist reflects grassroots anger, excellent piece by my #AFP colleague #FrankieTaggart http:\/\/t.co\/M47qJeoD",
"to_user": null,
"to_user_id": 0,
"to_user_id_str": "0",
"to_user_name": null
}
[....more....]
My /views/nepTweet/index.gsp is
<meta name='layout' content='main'/>
<b>${message}</b>
<p>Tweets</p>
<g:each in="${tweets}" var="tweet">
<p>${tweet.text}</p>
</g:each>
But, I get error parsing json to grails Map.
Error I get is :
Error 500: Internal Server Error
URI
/WhoTweetsNepal/nepTweet
Class
groovy.lang.MissingMethodException
Message
No signature of method: grails.converters.JSON.entrySet() is applicable for argument types: () values: [] Possible solutions: every()
I went through How do I access A JSON Object(String) from GSP page?, but couldn't get help.
Helpppp!!!
You definitely want
def tweetJson = JSON.parse(json);
(which will return a JSONObject, which is a Map) instead of
def tweetJson = new JSON(json) as Map;
but it looks like you have a bit of a name clash in your code - presumably the JSON in
http.request( GET, JSON )
is intended to be the HTTPBuilder content type rather than grails.converters.JSON. If you can clear up this name clash (i.e. remove the import static and say ContentType.JSON) then things may run more smoothly.
With to the point suggestions from Ian Roberts, I got the solution with my final Controller to be(realising there is no need to parse it) :
import grails.converters.*
import org.codehaus.groovy.grails.web.json.*; // package containing JSONObject, JSONArray,...
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
class NepTweetController {
def index() {
def restEndpointUrl = "http://search.twitter.com/search.json?q=%23nepal";
def http = new HTTPBuilder(restEndpointUrl);
// perform a GET request, expecting JSON response data
http.request( GET, ContentType.JSON ) {
//uri.path = '/search.json'
//uri.query = [ q: '%23nepal' ]
response.success = { resp, json ->
def tweetsResult = json.results;
render(view: "index", model: [message: "Request sent" , tweets: tweetsResult]);
}
}//end of request
}//end of method
}