[SOLVED] How to append the values generated from math.random function to a Json String? – Stack Overflow

Issue

This Content is from Stack Overflow. Question asked by Vidushika Dasanayka

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?



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


This Question was asked in StackOverflow by Vidushika Dasanayka and Answered by harl It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?