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

Time:09-19

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

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

CodePudding user response:

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}]}
  • Related