"results" : [
{
"geometry" : {
"location" : {
"lat" : 50.4501,
"lng" : 30.5234
},
"viewport" : {
"northeast" : {
"lat" : 50.59079800991073,
"lng" : 30.82594104187906
},
"southwest" : {
"lat" : 50.21327301525928,
"lng" : 30.23944009690609
}
}
},
There are lat and lng values in geometry, but i can get only into "results" for now.
JSONNode root = JSONNode.Parse(www.downloadHandler.text);
JSONArray nodes = root["results"].AsArray;
Might be better to use JsonElement which is faster. I have tested this code against your json and it works.
public static double UsingJsonElement(string jsonString)
{
var jsonElement = JsonSerializer.Deserialize<JsonElement>(jsonString);
return jsonElement
.GetProperty("geometry")
.GetProperty("location").GetProperty("lat")
.GetDouble();
var viewportlat = jsonElement
.GetProperty("geometry")
.GetProperty("viewport").GetProperty("northeas").GetProperty("lat")
.GetDouble();
}
According to your JSON hierarchy I guess it would depend on exactly which set of lat/long you are interested in - there are three.
And then afaik you simply go down the hierarchy like e.g.
var firstNode = nodes[0];
var geometry = firstNode["geometry"];
var location = geometry["location"];
var lat = location["lat"].AsFloat;
var lng = location["lng"].AsFloat;
You might want to rather use Newtonsoft JSON.Net though and simply implement according target type
[Serializable]
public class Root
{
public Node[] results;
}
[Serializable]
public class Node
{
// again depending which values you are interested in
// you only have to implement th hierarchy of values you care for
// the rest will be ignored
public Geometry geometry;
}
[Serializable]
public class Geometry
{
public Location location;
}
[Serializable]
public class Location
{
public float lat;
public float lng;
}
and then simply go
var nodes = JsonConvert.DeserializeObject<Root>(jsonString).results;
and access
var lat = nodes[0].geometry.location.lat;
var lng = nodes[0].geometry.location.lng;
Related
This is my JSON response in postman:
{
"result": {
"reviewcat": [
{
"id": 5
},
{
"id": 6
},
{
"id": 7
}
],
"reviewDet": {
"review_details": [
{
"review_point": "2.0"
},
{
"review_point": "4.5"
},
{
"review_point": "3",
}
],
for above response i have created model like below
public class BuyerReviewModel {
public var result : BuyserReviewResult?
}
public class BuyserReviewResult {
public var reviewcat : Array<Reviewcat>?
public var reviewDet : ReviewDet?
}
public class Reviewcat {
public var review_name : String?
public var id : Int?
}
public class ReviewDet {
public var review_details : Array<Review_details>?
}
public class Review_details {
public var review_cat_id : Int?
public var review_point : Float?
}
code: with this code i am getting only first review review_point val 2.5...how do i get 2nd review_point value 4.5 how?, could anybody guide me
class PostReviewVC: UIViewController {
#IBOutlet var rateImageViews: [UIImageView]!// 5 images array
#IBOutlet var rateButtons: [UIButton]!// 5 buttons array
var rateFatched: Float = 0.0
private var testData = ReviewModel(dictionary: NSDictionary()){
didSet{
titleLbl.text = byuReviewData?.result?.enquiry?.comments
idLbl.text = byuReviewData?.result?.enquiry?.ref_no
userNameLbl.text = "\(byuReviewData?.result?.reviewDet?.get_to_user?.first_name ?? "") \(byuReviewData?.result?.reviewDet?.get_to_user?.last_name ?? "")"
if let data = testData?.result?.reviewDet{
for buyReviewData in data.review_details ?? []{
rateFatched = buyReviewData.review_point ?? 0.0
if rateFatched == NSString("2.5").floatValue{
for button in rateButtons {
if button.tag >= 2 {
allImages[button.tag].image = (#imageLiteral(resourceName: "staremp"))
}
else {
allImages[button.tag].image = (#imageLiteral(resourceName: "star"))
}
}
}
}
}
}
}
}
Since the main issue here seems to be how to get the correct data to display here is solution that focus on that but ignores any UI related stuff since I consider it off-topic.
I did some changes to the structure but nothing major, changed from class to struct, removed some optionals that didn't make sense and changed from var to let but feel free to change it back since it isn't really important to the answer.
public struct BuyserReviewResult {
public let reviewcat : [Reviewcat]
public let reviewDet : ReviewDet?
}
public struct Reviewcat {
public let review_name : String
public let id : Int
}
public struct ReviewDet {
public let review_details : [Review_details]
}
public struct Review_details {
public let review_cat_id : Int
public let review_point : Float
}
Now you can simply get each category name and the points for that category by doing
for category in result.reviewcat {
let points = result.reviewDet?.review_details
.first(where: { $0.review_cat_id == category.id })?.review_point ?? 0.0
print(category.review_name, points)
}
Note that also ignored the top level type here since it is no longer needed once you have parsed the data.
Yes the review_point is of type String and not Float, as suggested by #burnsi
After getting the string value you can always parse it to Float
I am trying to get a specific value from a Bson document using an IQueryable object. I have a method that is reading a json structure as shown below.
"SimulatedData": [
{
"value": 1819.00923045901,
"units": "hp",
"tag": "comp/totalIhp",
"name": "Compressor - Total IHP"
},
{
"value": 789.294125,
"units": "RPM",
"tag": "comp/averageSpeed",
"name": "Compressor - Speed"
},
{
"value": 2064.74658240481,
"units": "hp",
"tag": "comp/totalBhp",
"name": "Compressor - Total BHP"
}
]
I am reading this JSON, getting the 'tag' key value and then looking for this tag value in a collection in MongoDB.
try
{
string jsonFromFile;
using (var reader = new StreamReader(path))
{
jsonFromFile = reader.ReadToEnd();
}
var simulatedData = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(jsonFromFile);
foreach (var channel in simulatedData.SimulatedData)
{
var tag = channel.tag;
var master = DBConnect.CosmosClient.GetCollection<MasterVariables>("MasterVariables");
var channelId = master.AsQueryable().Where(x => x.Tag == $"{tag}");
foreach(var c in channelId)
{
string id = c.ChannelID;
Console.WriteLine(id);
}
}
}
The value of the 'tag' key will be used to search in MasterVariables for a match. The document in MasterVariables that matches the value of the 'tag' key will result in a JSON/bson as below.I have a class that take in these values and sets them to class attributes
{
"Tag" : "comp/idealTotalSucCapacity",
"Group" : "{ id : \"comp\", parent : \"#\", text : \"Compressor\" }",
"Series" : "Compressor",
"Enabled" : true,
"ChannelID" : "C8",
"productType" : "Spotlight_Comp",
"database" : "compdata"
}
MasterVariables class (below)
public class MasterVariables
{
public string Tag { get; set; }
public string Group { get; set; }
public string Series { get; set; }
public bool Enabled { get; set; }
public string ChannelID { get; set; }
public string productType { get; set; }
public string database { get; set; }
}
My main issue is that I am not able to get the "ChannelID" value using c.ChannelID . My code compiles and doesn't give me any errors. But I am very confused as to why I am not able to get the channelID value using an Iqueryable object. I know the below foreach isn't correct since I will only be receiving 1 Bson document that matches the 'tag' value. But I haven't found anything helpful about a different way to get the ChannelId. Any thoughts on what I am doing wrong here? Or is there a different approach?
foreach(var c in channelId)
{
string id = c.ChannelID;
Console.WriteLine(id);
}
Angular requires Date objects in many places whereas JSON contains string representation of the date.
I want to add an array of properties which contain date values:
class Foo
{
public int IntProp {get;set;}
public DateTime? Prop1 {get;set;}
public DateTime Prop2 {get;set;}
public Bar Bar {set;set;}
}
class Bar
{
public DateTime Prop {get;set;}
public IEnumerable<DateTime?> Dates {get;set;}
}
Foo should then be serialized like this:
{
"IntProp": 1,
"Prop1": "...",
"Prop2": "...",
"Bar": {
"Prop": "..."
},
"<Dates>": [ "Prop1", "Prop2", "Bar.Prop", "Bar.Dates"]
}
This allows me to automatically convert strings to date objects at the client side without testing every property whether it is convertible to Date like it is described in this question.
I can collect the paths of date properties, but have no idea how to add populated array to the root.
You could convert to an intermediate JObject and add the property there. For instance, given the following converter:
public class PathLoggingDateTimeConverter : IsoDateTimeConverter
{
public const string DatePathPropertyName = "<Dates>";
readonly List<string> paths = new List<string>();
public override bool CanConvert(Type objectType)
{
if (!base.CanConvert(objectType))
return false;
// Not for DateTimeOffset
return objectType == typeof(DateTime) || objectType == typeof(DateTime?);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
base.WriteJson(writer, value, serializer);
if (value != null)
paths.Add(writer.Path);
}
public IList<string> Paths { get { return paths; } }
}
You can do:
var root = new Foo
{
IntProp = 101,
Prop1 = DateTime.Today.ToUniversalTime(),
Prop2 = DateTime.Today.ToUniversalTime(),
Bar = new Bar
{
Prop = DateTime.Today.ToUniversalTime(),
Dates = new List<DateTime?> { null, DateTime.Today.ToUniversalTime() },
},
};
var converter = new PathLoggingDateTimeConverter();
var settings = new JsonSerializerSettings { Converters = new[] { converter } };
var obj = JObject.FromObject(root, JsonSerializer.CreateDefault(settings));
obj[PathLoggingDateTimeConverter.DatePathPropertyName] = JToken.FromObject(converter.Paths);
Console.WriteLine(obj);
And the result is:
{
"IntProp": 101,
"Prop1": "2016-10-25T04:00:00Z",
"Prop2": "2016-10-25T04:00:00Z",
"Bar": {
"Prop": "2016-10-25T04:00:00Z",
"Dates": [
null,
"2016-10-25T04:00:00Z"
]
},
"<Dates>": [
"Prop1",
"Prop2",
"Bar.Prop",
"Bar.Dates[1]"
]
}
In a MongoDB I have a collection with documents with this structure:
{
"_id" : 18,
"name" : "Verdell Sowinski",
"scores" : [
{
"type" : "exam",
"score" : 62.12870233109035
},
{
"type" : "quiz",
"score" : 84.74586220889356
},
{
"type" : "homework",
"score" : 81.58947824932574
},
{
"type" : "homework",
"score" : 69.09840625499065
}
]
}
I am using .NET. I need to remove the scores array element with the lowest scores.score for all the documents with scores.type="homework".
In the example would be the 4th element of the scores array ("score" : 69.09840625499065).
I suposse I have to group by Id, sort limiting to 1 and then use the method DeleteMany but I can´t get the code work
I can`t solve the problem. The code I´m trying and don't work is the next one:
var db = client.GetDatabase("school");
var col = db.GetCollection<Student>("students");
var filter = new BsonDocument("scores.type", "homework");
var myresult = await col
//.Find(filter)
.Aggregate()
.Unwind(x => x.Scores)
.Group(new BsonDocument { { "_id", "$_id" },
{ "minimo", new BsonDocument("$min", "$Scores.score") } })
.Sort(new BsonDocument("minimo", -1))
.Limit(1)
.ToListAsync();
My classes:
public class Student
{
public int _id { get; set; }
public string Name { get; set; }
public List<Score> Scores { get; set; }
}
public class Score
{
public string Type { get; set; }
public double Mark { get; set; }
}
I have the following object:
{
"id" : "sampleId";
foos : [{
"prop1":"value1",
"prop2":"value2"
},
{
"prop1":"value3",
"prop2":"value4"
}
]}
How can I get foos, where prop2 is value4? I'm using Spring data mongodb.
If you use spring data mongodb repositories, it can make your life easy. You will need a domain class. e.g.
public class Foo {
String prop1;
String prop2;
}
public class MyClass {
String id;
List<Foo> foos;
}
public interface MyClassRepository extends MongoRepository<MyClass, String> {
List<MyClass> findByFoosProp2(String prop2ValueToLookFor);
// assuming you can find multiple matches
}
Then simply call this method from your code
public clsss SomeBusinessClass {
#Autowired
private MyClassRepository repository;
public void mySomeBusinessMethod() {
List<MyClass> myObjects = repository.findByFoosProp2("value4");
}
}
This code will return a SampleBean with id sampleId wich will have only matching items in collection foos.
// Match one document with sampleId
Query q1 = new Query(where("id").is("sampleId"));
// match only foos with prop2 value value2
Query q2 = query(where("foos").elemMatch(where("prop2").is("value2))
BasicQuery query = new BasicQuery(q1.getQueryObject(), q2.getQueryObject());
SampleBean result = mongoTemplate.findOne(query, SampleBean.class)