Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to append the values generated from math.random function to a Json String?

I’m working on java project where I want to create a json string which I need to include the random values generated from math.random function to that particular json string.

  String string=("{\"Id\":1,\"Ref\":
 'device1',\"telemetryAttributeRef\":'temperature',\"telemetryAttributeData\":[{\"value\":%.2f,\"ts\":1655295919}]}",Math.random()*50);

But here I’m getting error as,

Math cannot be resolved or is not a filed

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can someone help me to attach the random values to the json string?

>Solution :

do it like this:

String string = "{\"Id\":1,\"Ref\":\"device1\",\"telemetryAttributeRef\":\"temperature\",\"telemetryAttributeData\":[{\"value\":%.2f,\"ts\":1655295919}]}";
String result = String.format(string, Math.random() * 50);
System.out.println(result);

hear is the result:

{"Id":1,"Ref":"device1","telemetryAttributeRef":"temperature","telemetryAttributeData":[{"value":16.75,"ts":1655295919}]}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading