Unable to get json node values - json

This is the json response format that I have and need to read the first node value "html". I have tried to few ways to get the value but unable to get it
[
{
"html": "<!DOCTYPE html>\n <html>\n <head>\n <\/html>\n \n",
<\/html>\n \n",
"headers": {},
"subject": "Register new account",
"messageId": "475603953.247.1565607800153#dfrsbdd201.abc.com.au",
"priority": "normal",
"from": [],
"to": [],
"date": "2019-08-12T11:03:20.000Z",
"receivedDate": "2019-08-12T11:09:42.000Z",
"receivedAt": "2019-08-12T11:09:44.900Z"
},
{+},
{+}
]
I tried couple of things
RequestSpecification emailReq = given().with().pathParam("email",emailName);
Response emailResp = emailReq.contentType("application/json").get("https://restmail.net/mail/{email}");
JSONObject value = new JSONObject(emailResp.asString());
I got this error
org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:505)
and then I removed this last line to use But this does not gives me error. pls refer screenshot for this
JSONArray responseJson = new JSONArray(emailResp.asString());
Tried this as well
List<HashMap<String, Object>> jsonObjectsInArray = emailResp.jsonPath().getList("$");
for (HashMap<String, Object> singleLeg : jsonObjectsInArray) {
String value = (String) singleLeg.get("html");
}
But again array size is 0
Need some suggestion of how to get the value of node - "html". Pls suggest. what mistake am I doing here?
Thanks in advance

RequestSpecification emailReq = given().with().pathParam("email",emailName);
int retries = 5;
List<HashMap<String, Object>> emails = Arrays.asList();
. . .
emailResp = emailReq.get("restmail.net/mail{email}");
if (emailResp.getStatusCode() == 200) { emails = emailResp.jsonPath().getList("$");
String email = emails.get(0).get("html").toString();

Related

Unhandled Exception: type 'String' is not a subtype of type 'List<dynamic>'

I'm trying to parse the images from images from the json response, but I'm getting as error stating as Unhandled Exception: type 'String' is not a subtype of type 'List'
{
"status": true,
"record": {
"adid": "3",
"adsubcatid": "7",
"aduserid": "2",
"adname": "wfw fw",
"adcoverimg": "http://codecell.in/girrivi/assets/adcover/ic_service_search.png",
"addesc": "e fe fe ",
"ads_price": "5000",
"ads_location": "mysuru",
"created_date": "13/10/2020",
"user_name": "sunil",
"images": "{'adsimg_img':'http://codecell.in/girrivi/assets/adimgs/carpenter.png'},{'adsimg_img':'http://codecell.in/girrivi/assets/adimgs/electrician.png'},{'adsimg_img':'http://codecell.in/girrivi/assets/adimgs/gardner.png'}"
}
}
List images;
Future<String> getProductDetails() async {
String productDetailsUrl = Constant.productDetailsUrl+widget.id;
print(productDetailsUrl);
Map<String, String> headers = {'Content-Type' : 'application/json'};
final response = await http.get(productDetailsUrl, headers: headers);
print(response.body);
if(response.statusCode == 200){
jsonResponse = json.decode(response.body);
print('Response in Profile Screen: ' + response.body);
print("Price - "+jsonResponse['record']['ads_price']);
setState(() {
price = jsonResponse['record']['ads_price'];
title = jsonResponse['record']['adname'];
description = jsonResponse['record']['addesc'];
location = jsonResponse['record']['ads_location'];
publishedOn = jsonResponse['record']['created_date'];
postedBy = jsonResponse['record']['user_name'];
adId = jsonResponse['record']['adid'];
postedById = jsonResponse['record']['aduserid'];
images = jsonResponse['record']['images'];
});
}
}
I am getting all the details in the right way except the images
As I see in your images response you have this {'adsimg_img': 'some_url'}.
So I would do like this in your code
setState(() {
.
.
.
adId = jsonResponse['record']['adid'];
postedById = jsonResponse['record']['aduserid'];
images = (jsonResponse['record']['images'] as List)
?.map((i) => i['adsimg_img'])
?.toList();
});
So images at the end will look like ['url1', 'url2', ...] // List of Strings
I didn't tested it but it should do the trick :)
In the json response snippet that you have added, the value of images should be an array, but it is in double quotes which is a basically string.
If you put that snippet into a jsonValidator like this one, it shows that the value of the key images is a string, rather than the array that you are expecting.
An array of objects in json is formatted like in this one
{
"user_name": "sunil",
"images": [
{
"adsimg_img":"http://codecell.in/girrivi/assets/adimgs/carpenter.png"
},
{
"adsimg_img":"http://codecell.in/girrivi/assets/adimgs/carpenter.png"
},
{
"adsimg_img":"http://codecell.in/girrivi/assets/adimgs/carpenter.png"
}
]
}

How to send 'JSON' in post request using deluge?

I have a JSON data, which i need to pass it in POST method. I have no idea how to convert JSON data as query paramters. Kindly help me how to send this type of a JSON data in POST method using deluge.
jsonData = {
"author": "urn:li:person:12345",
"lifecycleState": "PUBLISHED",
"specificContent": {
"com.linkedin.ugc.ShareContent": {
"shareCommentary": {
"text": "Hello World! This is my first Share on LinkedIn!"
},
"shareMediaCategory": "NONE"
}
},
"visibility": {
"com.linkedin.ugc.MemberNetworkVisibility": "PUBLIC"
}
}
This is what i actually tried:
headerData = Map();
headerData.put("Content-Type","application/json charset=utf-8");
headerData.put("X-Restli-Protocol-Version","2.0.0");
headerData.put("x-li-format","json");
//json data
fields = "{\"author\":\"urn:li:person:368964147\",\"lifecycleState\":\"PUBLISHED\",\"specificContent\": {\"com.linkedin.ugc.ShareContent\":{\"shareCommentary\":{\"text\": \"Hello World! This is my first Share on LinkedIn!\"},\"shareMediaCategory\": \"NONE\"}},\"visibility\":{\"com.linkedin.ugc.MemberNetworkVisibility\":\"PUBLIC\"}}";
//info fields;
response = invokeurl
[
url :"https://api.linkedin.com/v2/ugcPosts"
type :POST
parameters:fields
headers:headerData
connection:"li"
];
info response;
I expect:
params = Map();
params.put("author","urn:li:person:12345");
params.put("lifecycleState","PUBLISHED");
...so on
Thanks.
I found the deluge code to convert JSON data to query parameters.
param = Map();
param.put("author","urn:li:person:YoTjU8Fmfk");
param.put("lifecycleState","PUBLISHED");
specificContent = Map();
ShareContent = Map();
shareCommentary = Map();
shareCommentary.put("text","Hello World! This is my first Share on LinkedIn!");
ShareContent.put("shareCommentary",shareCommentary);
specificContent.put("com.linkedin.ugc.ShareContent",ShareContent);
specificContent.put("shareMediaCategory","NONE");
param.put("specificContent",specificContent);
visibility = Map();
visibility.put("com.linkedin.ugc.MemberNetworkVisibility","PUBLIC");
param.put("visibility",visibility);

UWP - From Json string to Structure (Classes)

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 ...

Parsing nested arrays in JSON data swift

I'm currently working with trying to extract bits of information from a complicated json based database. After NSJSONSerialization.JSONObjectWithData I get output like follows (some returns added for clarity)
[
"title": Recorder Suite In A Minor - Viola Concerto - Tafelmusik,
"estimated_weight": 85,
"year": 0,
"thumb": ,
"identifiers": <__NSArrayI 0x600000089970>(
{
description = Text;
type = Barcode;
value = 4891030501560;
},
{
description = Printed;
type = Barcode;
value = "4 891030 501560";
},
{
type = ASIN;
value = B0000013L9;
},
{
type = "Mould SID Code";
value = "ifpi 8412";
},
{
type = "Matrix / Runout";
value = "CD PLANT AB 8550156 CDM01";
},
{
description = "SPARS Code";
type = Other;
value = DDD;
},
{
type = "Label Code";
value = "LC 9158";
}
),
"id": 885370,
"date_changed": 2014-06-17T03:53:03-07:00,
"master_url": https://api.discogs.com/masters/495830,
etc … ]
In particular, I need to know how to get the information out of the nested array. Note that the array is not (obviously) a nested dictionary - given the equal signs and the repeated keys. Any help with how to parse this would be appreciated.
I would use a Pod like SwiftyJSON.
First, you need to install CocoaPods, and then go for SwiftyJSON.
I would parse nested arrays in the following manner:
let json = JSON(data: dataFromNetworking)
if let items = json["items"].array {
for item in items {
if let title = item["title"].string {
println(title)
}
}
}
Check out the documentation and Usage section of SwiftyJSON for more info.
Cheers...

How to use JObject.FromObject to get a json with no propertyname

I use NewtonSoft JSON.Net. I have a collection of namevalue pair and i need to get a json that looks like
{"cot":"1","mac":"2","cot":"8"}
Note that i can have duplicate names here.
I have two options here
a) i can use Dictionary as my underlying collection and when i do, i get the desired result but i cant add duplicate key.
b) i have have a list of KeyValuePair but in this case, the result json is not in the structure i wanted.
Any idea how to get the desired result? thanks!
var listData = new List<KeyValuePair<string, string>>();
listData.Add(new KeyValuePair<string, string>("cot", "1"));
listData.Add(new KeyValuePair<string, string>("mat", "1"));
listData.Add(new KeyValuePair<string, string>("cot", "2"));
var dicData = new Dictionary<string, string>();
dicData.Add("cot", "1");
dicData.Add("mat", "1");
Console.WriteLine("Output from LIST");
Console.WriteLine(JArray.FromObject(listData));
Console.WriteLine();
Console.WriteLine("Output from Dictionary");
Console.WriteLine(JObject.FromObject(dicData));
Output from LIST
[
{
"Key": "cot",
"Value": "1"
},
{
"Key": "mat",
"Value": "1"
},
{
"Key": "cot",
"Value": "2"
}
]
Output from Dictionary
{
"cot": "1",
"mat": "1"
}
The JSON
'{"cot":"1","mac":"2","cot":"8"}'
will parse to a javscript object :
{"cot":"8","mac":"2"}.
Try
dicData.Add("cot", "8")
and see if it gets what you want.
You can also try concatenating strings until you get the desired JSON.
Like
var jsonOutput = "{"
//for each key value...
jsonOutput += "key : "+ value.toString + ","
//...etc
//then remove the last trailing comma, and add a "}"